repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
opal/opal
lib/opal/compiler.rb
Opal.Compiler.unique_temp
def unique_temp(name) name = name.to_s if name && !name.empty? name = name .to_s .gsub('<=>', '$lt_eq_gt') .gsub('===', '$eq_eq_eq') .gsub('==', '$eq_eq') .gsub('=~', '$eq_tilde') .gsub('!~', '$excl_tilde') .gsub('!=', '$not_eq') .gsub('<=', '$lt_eq') .gsub('>=', '$gt_eq') .gsub('=', '$eq') .gsub('?', '$ques') .gsub('!', '$excl') .gsub('/', '$slash') .gsub('%', '$percent') .gsub('+', '$plus') .gsub('-', '$minus') .gsub('<', '$lt') .gsub('>', '$gt') .gsub(/[^\w\$]/, '$') end unique = (@unique += 1) "#{'$' unless name.start_with?('$')}#{name}$#{unique}" end
ruby
def unique_temp(name) name = name.to_s if name && !name.empty? name = name .to_s .gsub('<=>', '$lt_eq_gt') .gsub('===', '$eq_eq_eq') .gsub('==', '$eq_eq') .gsub('=~', '$eq_tilde') .gsub('!~', '$excl_tilde') .gsub('!=', '$not_eq') .gsub('<=', '$lt_eq') .gsub('>=', '$gt_eq') .gsub('=', '$eq') .gsub('?', '$ques') .gsub('!', '$excl') .gsub('/', '$slash') .gsub('%', '$percent') .gsub('+', '$plus') .gsub('-', '$minus') .gsub('<', '$lt') .gsub('>', '$gt') .gsub(/[^\w\$]/, '$') end unique = (@unique += 1) "#{'$' unless name.start_with?('$')}#{name}$#{unique}" end
[ "def", "unique_temp", "(", "name", ")", "name", "=", "name", ".", "to_s", "if", "name", "&&", "!", "name", ".", "empty?", "name", "=", "name", ".", "to_s", ".", "gsub", "(", "'<=>'", ",", "'$lt_eq_gt'", ")", ".", "gsub", "(", "'==='", ",", "'$eq_eq_eq'", ")", ".", "gsub", "(", "'=='", ",", "'$eq_eq'", ")", ".", "gsub", "(", "'=~'", ",", "'$eq_tilde'", ")", ".", "gsub", "(", "'!~'", ",", "'$excl_tilde'", ")", ".", "gsub", "(", "'!='", ",", "'$not_eq'", ")", ".", "gsub", "(", "'<='", ",", "'$lt_eq'", ")", ".", "gsub", "(", "'>='", ",", "'$gt_eq'", ")", ".", "gsub", "(", "'='", ",", "'$eq'", ")", ".", "gsub", "(", "'?'", ",", "'$ques'", ")", ".", "gsub", "(", "'!'", ",", "'$excl'", ")", ".", "gsub", "(", "'/'", ",", "'$slash'", ")", ".", "gsub", "(", "'%'", ",", "'$percent'", ")", ".", "gsub", "(", "'+'", ",", "'$plus'", ")", ".", "gsub", "(", "'-'", ",", "'$minus'", ")", ".", "gsub", "(", "'<'", ",", "'$lt'", ")", ".", "gsub", "(", "'>'", ",", "'$gt'", ")", ".", "gsub", "(", "/", "\\w", "\\$", "/", ",", "'$'", ")", "end", "unique", "=", "(", "@unique", "+=", "1", ")", "\"#{'$' unless name.start_with?('$')}#{name}$#{unique}\"", "end" ]
Used to generate a unique id name per file. These are used mainly to name method bodies for methods that use blocks.
[ "Used", "to", "generate", "a", "unique", "id", "name", "per", "file", ".", "These", "are", "used", "mainly", "to", "name", "method", "bodies", "for", "methods", "that", "use", "blocks", "." ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/lib/opal/compiler.rb#L270-L296
train
opal/opal
lib/opal/compiler.rb
Opal.Compiler.process
def process(sexp, level = :expr) return fragment('', scope) if sexp.nil? if handler = handlers[sexp.type] return handler.new(sexp, level, self).compile_to_fragments else error "Unsupported sexp: #{sexp.type}" end end
ruby
def process(sexp, level = :expr) return fragment('', scope) if sexp.nil? if handler = handlers[sexp.type] return handler.new(sexp, level, self).compile_to_fragments else error "Unsupported sexp: #{sexp.type}" end end
[ "def", "process", "(", "sexp", ",", "level", "=", ":expr", ")", "return", "fragment", "(", "''", ",", "scope", ")", "if", "sexp", ".", "nil?", "if", "handler", "=", "handlers", "[", "sexp", ".", "type", "]", "return", "handler", ".", "new", "(", "sexp", ",", "level", ",", "self", ")", ".", "compile_to_fragments", "else", "error", "\"Unsupported sexp: #{sexp.type}\"", "end", "end" ]
Process the given sexp by creating a node instance, based on its type, and compiling it to fragments.
[ "Process", "the", "given", "sexp", "by", "creating", "a", "node", "instance", "based", "on", "its", "type", "and", "compiling", "it", "to", "fragments", "." ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/lib/opal/compiler.rb#L354-L362
train
opal/opal
lib/opal/compiler.rb
Opal.Compiler.returns
def returns(sexp) return returns s(:nil) unless sexp case sexp.type when :undef # undef :method_name always returns nil returns s(:begin, sexp, s(:nil)) when :break, :next, :redo sexp when :yield sexp.updated(:returnable_yield, nil) when :when *when_sexp, then_sexp = *sexp sexp.updated(nil, [*when_sexp, returns(then_sexp)]) when :rescue body_sexp, *resbodies, else_sexp = *sexp resbodies = resbodies.map do |resbody| returns(resbody) end if else_sexp else_sexp = returns(else_sexp) end sexp.updated( nil, [ returns(body_sexp), *resbodies, else_sexp ] ) when :resbody klass, lvar, body = *sexp sexp.updated(nil, [klass, lvar, returns(body)]) when :ensure rescue_sexp, ensure_body = *sexp sexp = sexp.updated(nil, [returns(rescue_sexp), ensure_body]) s(:js_return, sexp) when :begin, :kwbegin # Wrapping last expression with s(:js_return, ...) *rest, last = *sexp sexp.updated(nil, [*rest, returns(last)]) when :while, :until, :while_post, :until_post sexp when :return, :js_return, :returnable_yield sexp when :xstr sexp.updated(nil, [s(:js_return, *sexp.children)]) when :if cond, true_body, false_body = *sexp sexp.updated( nil, [ cond, returns(true_body), returns(false_body) ] ) else s(:js_return, sexp).updated( nil, nil, location: sexp.loc, ) end end
ruby
def returns(sexp) return returns s(:nil) unless sexp case sexp.type when :undef # undef :method_name always returns nil returns s(:begin, sexp, s(:nil)) when :break, :next, :redo sexp when :yield sexp.updated(:returnable_yield, nil) when :when *when_sexp, then_sexp = *sexp sexp.updated(nil, [*when_sexp, returns(then_sexp)]) when :rescue body_sexp, *resbodies, else_sexp = *sexp resbodies = resbodies.map do |resbody| returns(resbody) end if else_sexp else_sexp = returns(else_sexp) end sexp.updated( nil, [ returns(body_sexp), *resbodies, else_sexp ] ) when :resbody klass, lvar, body = *sexp sexp.updated(nil, [klass, lvar, returns(body)]) when :ensure rescue_sexp, ensure_body = *sexp sexp = sexp.updated(nil, [returns(rescue_sexp), ensure_body]) s(:js_return, sexp) when :begin, :kwbegin # Wrapping last expression with s(:js_return, ...) *rest, last = *sexp sexp.updated(nil, [*rest, returns(last)]) when :while, :until, :while_post, :until_post sexp when :return, :js_return, :returnable_yield sexp when :xstr sexp.updated(nil, [s(:js_return, *sexp.children)]) when :if cond, true_body, false_body = *sexp sexp.updated( nil, [ cond, returns(true_body), returns(false_body) ] ) else s(:js_return, sexp).updated( nil, nil, location: sexp.loc, ) end end
[ "def", "returns", "(", "sexp", ")", "return", "returns", "s", "(", ":nil", ")", "unless", "sexp", "case", "sexp", ".", "type", "when", ":undef", "returns", "s", "(", ":begin", ",", "sexp", ",", "s", "(", ":nil", ")", ")", "when", ":break", ",", ":next", ",", ":redo", "sexp", "when", ":yield", "sexp", ".", "updated", "(", ":returnable_yield", ",", "nil", ")", "when", ":when", "*", "when_sexp", ",", "then_sexp", "=", "*", "sexp", "sexp", ".", "updated", "(", "nil", ",", "[", "*", "when_sexp", ",", "returns", "(", "then_sexp", ")", "]", ")", "when", ":rescue", "body_sexp", ",", "*", "resbodies", ",", "else_sexp", "=", "*", "sexp", "resbodies", "=", "resbodies", ".", "map", "do", "|", "resbody", "|", "returns", "(", "resbody", ")", "end", "if", "else_sexp", "else_sexp", "=", "returns", "(", "else_sexp", ")", "end", "sexp", ".", "updated", "(", "nil", ",", "[", "returns", "(", "body_sexp", ")", ",", "*", "resbodies", ",", "else_sexp", "]", ")", "when", ":resbody", "klass", ",", "lvar", ",", "body", "=", "*", "sexp", "sexp", ".", "updated", "(", "nil", ",", "[", "klass", ",", "lvar", ",", "returns", "(", "body", ")", "]", ")", "when", ":ensure", "rescue_sexp", ",", "ensure_body", "=", "*", "sexp", "sexp", "=", "sexp", ".", "updated", "(", "nil", ",", "[", "returns", "(", "rescue_sexp", ")", ",", "ensure_body", "]", ")", "s", "(", ":js_return", ",", "sexp", ")", "when", ":begin", ",", ":kwbegin", "*", "rest", ",", "last", "=", "*", "sexp", "sexp", ".", "updated", "(", "nil", ",", "[", "*", "rest", ",", "returns", "(", "last", ")", "]", ")", "when", ":while", ",", ":until", ",", ":while_post", ",", ":until_post", "sexp", "when", ":return", ",", ":js_return", ",", ":returnable_yield", "sexp", "when", ":xstr", "sexp", ".", "updated", "(", "nil", ",", "[", "s", "(", ":js_return", ",", "*", "sexp", ".", "children", ")", "]", ")", "when", ":if", "cond", ",", "true_body", ",", "false_body", "=", "*", "sexp", "sexp", ".", "updated", "(", "nil", ",", "[", "cond", ",", "returns", "(", "true_body", ")", ",", "returns", "(", "false_body", ")", "]", ")", "else", "s", "(", ":js_return", ",", "sexp", ")", ".", "updated", "(", "nil", ",", "nil", ",", "location", ":", "sexp", ".", "loc", ",", ")", "end", "end" ]
The last sexps in method bodies, for example, need to be returned in the compiled javascript. Due to syntax differences between javascript any ruby, some sexps need to be handled specially. For example, `if` statemented cannot be returned in javascript, so instead the "truthy" and "falsy" parts of the if statement both need to be returned instead. Sexps that need to be returned are passed to this method, and the alterned/new sexps are returned and should be used instead. Most sexps can just be added into a `s(:return) sexp`, so that is the default action if no special case is required.
[ "The", "last", "sexps", "in", "method", "bodies", "for", "example", "need", "to", "be", "returned", "in", "the", "compiled", "javascript", ".", "Due", "to", "syntax", "differences", "between", "javascript", "any", "ruby", "some", "sexps", "need", "to", "be", "handled", "specially", ".", "For", "example", "if", "statemented", "cannot", "be", "returned", "in", "javascript", "so", "instead", "the", "truthy", "and", "falsy", "parts", "of", "the", "if", "statement", "both", "need", "to", "be", "returned", "instead", "." ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/lib/opal/compiler.rb#L390-L455
train
opal/opal
stdlib/racc/parser.rb
Racc.Parser.on_error
def on_error(t, val, vstack) raise ParseError, sprintf("\nparse error on value %s (%s)", val.inspect, token_to_str(t) || '?') end
ruby
def on_error(t, val, vstack) raise ParseError, sprintf("\nparse error on value %s (%s)", val.inspect, token_to_str(t) || '?') end
[ "def", "on_error", "(", "t", ",", "val", ",", "vstack", ")", "raise", "ParseError", ",", "sprintf", "(", "\"\\nparse error on value %s (%s)\"", ",", "val", ".", "inspect", ",", "token_to_str", "(", "t", ")", "||", "'?'", ")", "end" ]
This method is called when a parse error is found. ERROR_TOKEN_ID is an internal ID of token which caused error. You can get string representation of this ID by calling #token_to_str. ERROR_VALUE is a value of error token. value_stack is a stack of symbol values. DO NOT MODIFY this object. This method raises ParseError by default. If this method returns, parsers enter "error recovering mode".
[ "This", "method", "is", "called", "when", "a", "parse", "error", "is", "found", "." ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/stdlib/racc/parser.rb#L532-L535
train
opal/opal
stdlib/racc/parser.rb
Racc.Parser.racc_read_token
def racc_read_token(t, tok, val) @racc_debug_out.print 'read ' @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') ' @racc_debug_out.puts val.inspect @racc_debug_out.puts end
ruby
def racc_read_token(t, tok, val) @racc_debug_out.print 'read ' @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') ' @racc_debug_out.puts val.inspect @racc_debug_out.puts end
[ "def", "racc_read_token", "(", "t", ",", "tok", ",", "val", ")", "@racc_debug_out", ".", "print", "'read '", "@racc_debug_out", ".", "print", "tok", ".", "inspect", ",", "'('", ",", "racc_token2str", "(", "t", ")", ",", "') '", "@racc_debug_out", ".", "puts", "val", ".", "inspect", "@racc_debug_out", ".", "puts", "end" ]
For debugging output
[ "For", "debugging", "output" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/stdlib/racc/parser.rb#L555-L560
train
opal/opal
stdlib/benchmark.rb
Benchmark.Tms.memberwise
def memberwise(op, x) case x when Benchmark::Tms Benchmark::Tms.new(utime.__send__(op, x.utime), stime.__send__(op, x.stime), cutime.__send__(op, x.cutime), cstime.__send__(op, x.cstime), real.__send__(op, x.real) ) else Benchmark::Tms.new(utime.__send__(op, x), stime.__send__(op, x), cutime.__send__(op, x), cstime.__send__(op, x), real.__send__(op, x) ) end end
ruby
def memberwise(op, x) case x when Benchmark::Tms Benchmark::Tms.new(utime.__send__(op, x.utime), stime.__send__(op, x.stime), cutime.__send__(op, x.cutime), cstime.__send__(op, x.cstime), real.__send__(op, x.real) ) else Benchmark::Tms.new(utime.__send__(op, x), stime.__send__(op, x), cutime.__send__(op, x), cstime.__send__(op, x), real.__send__(op, x) ) end end
[ "def", "memberwise", "(", "op", ",", "x", ")", "case", "x", "when", "Benchmark", "::", "Tms", "Benchmark", "::", "Tms", ".", "new", "(", "utime", ".", "__send__", "(", "op", ",", "x", ".", "utime", ")", ",", "stime", ".", "__send__", "(", "op", ",", "x", ".", "stime", ")", ",", "cutime", ".", "__send__", "(", "op", ",", "x", ".", "cutime", ")", ",", "cstime", ".", "__send__", "(", "op", ",", "x", ".", "cstime", ")", ",", "real", ".", "__send__", "(", "op", ",", "x", ".", "real", ")", ")", "else", "Benchmark", "::", "Tms", ".", "new", "(", "utime", ".", "__send__", "(", "op", ",", "x", ")", ",", "stime", ".", "__send__", "(", "op", ",", "x", ")", ",", "cutime", ".", "__send__", "(", "op", ",", "x", ")", ",", "cstime", ".", "__send__", "(", "op", ",", "x", ")", ",", "real", ".", "__send__", "(", "op", ",", "x", ")", ")", "end", "end" ]
Returns a new Tms object obtained by memberwise operation +op+ of the individual times for this Tms object with those of the other Tms object. +op+ can be a mathematical operation such as <tt>+</tt>, <tt>-</tt>, <tt>*</tt>, <tt>/</tt>
[ "Returns", "a", "new", "Tms", "object", "obtained", "by", "memberwise", "operation", "+", "op", "+", "of", "the", "individual", "times", "for", "this", "Tms", "object", "with", "those", "of", "the", "other", "Tms", "object", "." ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/stdlib/benchmark.rb#L532-L549
train
opal/opal
lib/opal/config.rb
Opal.Config.config_option
def config_option(name, default_value, options = {}) compiler = options.fetch(:compiler_option, nil) valid_values = options.fetch(:valid_values, [true, false]) config_options[name] = { default: default_value, compiler: compiler } define_singleton_method(name) { config.fetch(name, default_value) } define_singleton_method("#{name}=") do |value| unless valid_values.any? { |valid_value| valid_value === value } raise ArgumentError, "Not a valid value for option #{self}.#{name}, provided #{value.inspect}. "\ "Must be #{valid_values.inspect} === #{value.inspect}" end config[name] = value end end
ruby
def config_option(name, default_value, options = {}) compiler = options.fetch(:compiler_option, nil) valid_values = options.fetch(:valid_values, [true, false]) config_options[name] = { default: default_value, compiler: compiler } define_singleton_method(name) { config.fetch(name, default_value) } define_singleton_method("#{name}=") do |value| unless valid_values.any? { |valid_value| valid_value === value } raise ArgumentError, "Not a valid value for option #{self}.#{name}, provided #{value.inspect}. "\ "Must be #{valid_values.inspect} === #{value.inspect}" end config[name] = value end end
[ "def", "config_option", "(", "name", ",", "default_value", ",", "options", "=", "{", "}", ")", "compiler", "=", "options", ".", "fetch", "(", ":compiler_option", ",", "nil", ")", "valid_values", "=", "options", ".", "fetch", "(", ":valid_values", ",", "[", "true", ",", "false", "]", ")", "config_options", "[", "name", "]", "=", "{", "default", ":", "default_value", ",", "compiler", ":", "compiler", "}", "define_singleton_method", "(", "name", ")", "{", "config", ".", "fetch", "(", "name", ",", "default_value", ")", "}", "define_singleton_method", "(", "\"#{name}=\"", ")", "do", "|", "value", "|", "unless", "valid_values", ".", "any?", "{", "|", "valid_value", "|", "valid_value", "===", "value", "}", "raise", "ArgumentError", ",", "\"Not a valid value for option #{self}.#{name}, provided #{value.inspect}. \"", "\"Must be #{valid_values.inspect} === #{value.inspect}\"", "end", "config", "[", "name", "]", "=", "value", "end", "end" ]
Defines a new configuration option @param [String] name the option name @param [Object] default_value the option's default value @!macro [attach] property @!attribute [rw] $1
[ "Defines", "a", "new", "configuration", "option" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/lib/opal/config.rb#L21-L39
train
opal/opal
opal/corelib/marshal/read_buffer.rb
Marshal.ReadBuffer.read_float
def read_float s = read_string(cache: false) result = if s == 'nan' 0.0 / 0 elsif s == 'inf' 1.0 / 0 elsif s == '-inf' -1.0 / 0 else s.to_f end @object_cache << result result end
ruby
def read_float s = read_string(cache: false) result = if s == 'nan' 0.0 / 0 elsif s == 'inf' 1.0 / 0 elsif s == '-inf' -1.0 / 0 else s.to_f end @object_cache << result result end
[ "def", "read_float", "s", "=", "read_string", "(", "cache", ":", "false", ")", "result", "=", "if", "s", "==", "'nan'", "0.0", "/", "0", "elsif", "s", "==", "'inf'", "1.0", "/", "0", "elsif", "s", "==", "'-inf'", "-", "1.0", "/", "0", "else", "s", ".", "to_f", "end", "@object_cache", "<<", "result", "result", "end" ]
Reads and returns Float from an input stream @example 123.456 Is encoded as 'f', '123.456'
[ "Reads", "and", "returns", "Float", "from", "an", "input", "stream" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/opal/corelib/marshal/read_buffer.rb#L155-L168
train
opal/opal
opal/corelib/marshal/read_buffer.rb
Marshal.ReadBuffer.read_bignum
def read_bignum sign = read_char == '-' ? -1 : 1 size = read_fixnum * 2 result = 0 (0...size).each do |exp| result += read_char.ord * 2**(exp * 8) end result = result.to_i * sign @object_cache << result result end
ruby
def read_bignum sign = read_char == '-' ? -1 : 1 size = read_fixnum * 2 result = 0 (0...size).each do |exp| result += read_char.ord * 2**(exp * 8) end result = result.to_i * sign @object_cache << result result end
[ "def", "read_bignum", "sign", "=", "read_char", "==", "'-'", "?", "-", "1", ":", "1", "size", "=", "read_fixnum", "*", "2", "result", "=", "0", "(", "0", "...", "size", ")", ".", "each", "do", "|", "exp", "|", "result", "+=", "read_char", ".", "ord", "*", "2", "**", "(", "exp", "*", "8", ")", "end", "result", "=", "result", ".", "to_i", "*", "sign", "@object_cache", "<<", "result", "result", "end" ]
Reads and returns Bignum from an input stream
[ "Reads", "and", "returns", "Bignum", "from", "an", "input", "stream" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/opal/corelib/marshal/read_buffer.rb#L172-L182
train
opal/opal
opal/corelib/marshal/read_buffer.rb
Marshal.ReadBuffer.read_regexp
def read_regexp string = read_string(cache: false) options = read_byte result = Regexp.new(string, options) @object_cache << result result end
ruby
def read_regexp string = read_string(cache: false) options = read_byte result = Regexp.new(string, options) @object_cache << result result end
[ "def", "read_regexp", "string", "=", "read_string", "(", "cache", ":", "false", ")", "options", "=", "read_byte", "result", "=", "Regexp", ".", "new", "(", "string", ",", "options", ")", "@object_cache", "<<", "result", "result", "end" ]
Reads and returns Regexp from an input stream @example r = /regexp/mix is encoded as '/', 'regexp', r.options.chr
[ "Reads", "and", "returns", "Regexp", "from", "an", "input", "stream" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/opal/corelib/marshal/read_buffer.rb#L311-L318
train
opal/opal
opal/corelib/marshal/read_buffer.rb
Marshal.ReadBuffer.read_struct
def read_struct klass_name = read(cache: false) klass = safe_const_get(klass_name) attributes = read_hash(cache: false) args = attributes.values_at(*klass.members) result = klass.new(*args) @object_cache << result result end
ruby
def read_struct klass_name = read(cache: false) klass = safe_const_get(klass_name) attributes = read_hash(cache: false) args = attributes.values_at(*klass.members) result = klass.new(*args) @object_cache << result result end
[ "def", "read_struct", "klass_name", "=", "read", "(", "cache", ":", "false", ")", "klass", "=", "safe_const_get", "(", "klass_name", ")", "attributes", "=", "read_hash", "(", "cache", ":", "false", ")", "args", "=", "attributes", ".", "values_at", "(", "*", "klass", ".", "members", ")", "result", "=", "klass", ".", "new", "(", "*", "args", ")", "@object_cache", "<<", "result", "result", "end" ]
Reads and returns a Struct from an input stream @example Point = Struct.new(:x, :y) Point.new(100, 200) is encoded as 'S', :Point, {:x => 100, :y => 200}
[ "Reads", "and", "returns", "a", "Struct", "from", "an", "input", "stream" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/opal/corelib/marshal/read_buffer.rb#L328-L336
train
opal/opal
opal/corelib/marshal/read_buffer.rb
Marshal.ReadBuffer.read_class
def read_class klass_name = read_string(cache: false) result = safe_const_get(klass_name) unless result.class == Class raise ArgumentError, "#{klass_name} does not refer to a Class" end @object_cache << result result end
ruby
def read_class klass_name = read_string(cache: false) result = safe_const_get(klass_name) unless result.class == Class raise ArgumentError, "#{klass_name} does not refer to a Class" end @object_cache << result result end
[ "def", "read_class", "klass_name", "=", "read_string", "(", "cache", ":", "false", ")", "result", "=", "safe_const_get", "(", "klass_name", ")", "unless", "result", ".", "class", "==", "Class", "raise", "ArgumentError", ",", "\"#{klass_name} does not refer to a Class\"", "end", "@object_cache", "<<", "result", "result", "end" ]
Reads and returns a Class from an input stream @example String is encoded as 'c', 'String'
[ "Reads", "and", "returns", "a", "Class", "from", "an", "input", "stream" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/opal/corelib/marshal/read_buffer.rb#L345-L353
train
opal/opal
opal/corelib/marshal/read_buffer.rb
Marshal.ReadBuffer.read_module
def read_module mod_name = read_string(cache: false) result = safe_const_get(mod_name) unless result.class == Module raise ArgumentError, "#{mod_name} does not refer to a Module" end @object_cache << result result end
ruby
def read_module mod_name = read_string(cache: false) result = safe_const_get(mod_name) unless result.class == Module raise ArgumentError, "#{mod_name} does not refer to a Module" end @object_cache << result result end
[ "def", "read_module", "mod_name", "=", "read_string", "(", "cache", ":", "false", ")", "result", "=", "safe_const_get", "(", "mod_name", ")", "unless", "result", ".", "class", "==", "Module", "raise", "ArgumentError", ",", "\"#{mod_name} does not refer to a Module\"", "end", "@object_cache", "<<", "result", "result", "end" ]
Reads and returns a Module from an input stream @example Kernel is encoded as 'm', 'Kernel'
[ "Reads", "and", "returns", "a", "Module", "from", "an", "input", "stream" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/opal/corelib/marshal/read_buffer.rb#L362-L370
train
opal/opal
opal/corelib/marshal/read_buffer.rb
Marshal.ReadBuffer.read_object
def read_object klass_name = read(cache: false) klass = safe_const_get(klass_name) object = klass.allocate @object_cache << object ivars = read_hash(cache: false) ivars.each do |name, value| if name[0] == '@' object.instance_variable_set(name, value) else # MRI allows an object to have ivars that do not start from '@' # https://github.com/ruby/ruby/blob/ab3a40c1031ff3a0535f6bcf26de40de37dbb1db/range.c#L1225 `object[name] = value` end end object end
ruby
def read_object klass_name = read(cache: false) klass = safe_const_get(klass_name) object = klass.allocate @object_cache << object ivars = read_hash(cache: false) ivars.each do |name, value| if name[0] == '@' object.instance_variable_set(name, value) else # MRI allows an object to have ivars that do not start from '@' # https://github.com/ruby/ruby/blob/ab3a40c1031ff3a0535f6bcf26de40de37dbb1db/range.c#L1225 `object[name] = value` end end object end
[ "def", "read_object", "klass_name", "=", "read", "(", "cache", ":", "false", ")", "klass", "=", "safe_const_get", "(", "klass_name", ")", "object", "=", "klass", ".", "allocate", "@object_cache", "<<", "object", "ivars", "=", "read_hash", "(", "cache", ":", "false", ")", "ivars", ".", "each", "do", "|", "name", ",", "value", "|", "if", "name", "[", "0", "]", "==", "'@'", "object", ".", "instance_variable_set", "(", "name", ",", "value", ")", "else", "`", "`", "end", "end", "object", "end" ]
Reads and returns an abstract object from an input stream @example obj = Object.new obj.instance_variable_set(:@ivar, 100) obj is encoded as 'o', :Object, {:@ivar => 100} The only exception is a Range class (and its subclasses) For some reason in MRI isntances of this class have instance variables - begin - end - excl without '@' perfix.
[ "Reads", "and", "returns", "an", "abstract", "object", "from", "an", "input", "stream" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/opal/corelib/marshal/read_buffer.rb#L388-L407
train
opal/opal
opal/corelib/marshal/read_buffer.rb
Marshal.ReadBuffer.read_extended_object
def read_extended_object mod = safe_const_get(read) object = read object.extend(mod) object end
ruby
def read_extended_object mod = safe_const_get(read) object = read object.extend(mod) object end
[ "def", "read_extended_object", "mod", "=", "safe_const_get", "(", "read", ")", "object", "=", "read", "object", ".", "extend", "(", "mod", ")", "object", "end" ]
Reads an object that was dynamically extended before marshaling like @example M1 = Module.new M2 = Module.new obj = Object.new obj.extend(M1) obj.extend(M2) obj is encoded as 'e', :M2, :M1, obj
[ "Reads", "an", "object", "that", "was", "dynamically", "extended", "before", "marshaling", "like" ]
41aedc0fd62aab00d3c117ba0caf00206bedd981
https://github.com/opal/opal/blob/41aedc0fd62aab00d3c117ba0caf00206bedd981/opal/corelib/marshal/read_buffer.rb#L437-L442
train
SamSaffron/memory_profiler
lib/memory_profiler/reporter.rb
MemoryProfiler.Reporter.run
def run(&block) start begin yield rescue Exception ObjectSpace.trace_object_allocations_stop GC.enable raise else stop end end
ruby
def run(&block) start begin yield rescue Exception ObjectSpace.trace_object_allocations_stop GC.enable raise else stop end end
[ "def", "run", "(", "&", "block", ")", "start", "begin", "yield", "rescue", "Exception", "ObjectSpace", ".", "trace_object_allocations_stop", "GC", ".", "enable", "raise", "else", "stop", "end", "end" ]
Collects object allocation and memory of ruby code inside of passed block.
[ "Collects", "object", "allocation", "and", "memory", "of", "ruby", "code", "inside", "of", "passed", "block", "." ]
bd87ff68559623d12c827800ee795475db4d5b8b
https://github.com/SamSaffron/memory_profiler/blob/bd87ff68559623d12c827800ee795475db4d5b8b/lib/memory_profiler/reporter.rb#L71-L82
train
SamSaffron/memory_profiler
lib/memory_profiler/reporter.rb
MemoryProfiler.Reporter.object_list
def object_list(generation) rvalue_size = GC::INTERNAL_CONSTANTS[:RVALUE_SIZE] helper = Helpers.new result = StatHash.new.compare_by_identity ObjectSpace.each_object do |obj| next unless ObjectSpace.allocation_generation(obj) == generation file = ObjectSpace.allocation_sourcefile(obj) || "(no name)" next if @ignore_files && @ignore_files =~ file next if @allow_files && !(@allow_files =~ file) klass = obj.class rescue nil unless Class === klass # attempt to determine the true Class when .class returns something other than a Class klass = Kernel.instance_method(:class).bind(obj).call end next if @trace && !trace.include?(klass) begin line = ObjectSpace.allocation_sourceline(obj) location = helper.lookup_location(file, line) class_name = helper.lookup_class_name(klass) gem = helper.guess_gem(file) # we do memsize first to avoid freezing as a side effect and shifting # storage to the new frozen string, this happens on @hash[s] in lookup_string memsize = ObjectSpace.memsize_of(obj) string = klass == String ? helper.lookup_string(obj) : nil # compensate for API bug memsize = rvalue_size if memsize > 100_000_000_000 result[obj.__id__] = MemoryProfiler::Stat.new(class_name, gem, file, location, memsize, string) rescue # give up if any any error occurs inspecting the object end end result end
ruby
def object_list(generation) rvalue_size = GC::INTERNAL_CONSTANTS[:RVALUE_SIZE] helper = Helpers.new result = StatHash.new.compare_by_identity ObjectSpace.each_object do |obj| next unless ObjectSpace.allocation_generation(obj) == generation file = ObjectSpace.allocation_sourcefile(obj) || "(no name)" next if @ignore_files && @ignore_files =~ file next if @allow_files && !(@allow_files =~ file) klass = obj.class rescue nil unless Class === klass # attempt to determine the true Class when .class returns something other than a Class klass = Kernel.instance_method(:class).bind(obj).call end next if @trace && !trace.include?(klass) begin line = ObjectSpace.allocation_sourceline(obj) location = helper.lookup_location(file, line) class_name = helper.lookup_class_name(klass) gem = helper.guess_gem(file) # we do memsize first to avoid freezing as a side effect and shifting # storage to the new frozen string, this happens on @hash[s] in lookup_string memsize = ObjectSpace.memsize_of(obj) string = klass == String ? helper.lookup_string(obj) : nil # compensate for API bug memsize = rvalue_size if memsize > 100_000_000_000 result[obj.__id__] = MemoryProfiler::Stat.new(class_name, gem, file, location, memsize, string) rescue # give up if any any error occurs inspecting the object end end result end
[ "def", "object_list", "(", "generation", ")", "rvalue_size", "=", "GC", "::", "INTERNAL_CONSTANTS", "[", ":RVALUE_SIZE", "]", "helper", "=", "Helpers", ".", "new", "result", "=", "StatHash", ".", "new", ".", "compare_by_identity", "ObjectSpace", ".", "each_object", "do", "|", "obj", "|", "next", "unless", "ObjectSpace", ".", "allocation_generation", "(", "obj", ")", "==", "generation", "file", "=", "ObjectSpace", ".", "allocation_sourcefile", "(", "obj", ")", "||", "\"(no name)\"", "next", "if", "@ignore_files", "&&", "@ignore_files", "=~", "file", "next", "if", "@allow_files", "&&", "!", "(", "@allow_files", "=~", "file", ")", "klass", "=", "obj", ".", "class", "rescue", "nil", "unless", "Class", "===", "klass", "klass", "=", "Kernel", ".", "instance_method", "(", ":class", ")", ".", "bind", "(", "obj", ")", ".", "call", "end", "next", "if", "@trace", "&&", "!", "trace", ".", "include?", "(", "klass", ")", "begin", "line", "=", "ObjectSpace", ".", "allocation_sourceline", "(", "obj", ")", "location", "=", "helper", ".", "lookup_location", "(", "file", ",", "line", ")", "class_name", "=", "helper", ".", "lookup_class_name", "(", "klass", ")", "gem", "=", "helper", ".", "guess_gem", "(", "file", ")", "memsize", "=", "ObjectSpace", ".", "memsize_of", "(", "obj", ")", "string", "=", "klass", "==", "String", "?", "helper", ".", "lookup_string", "(", "obj", ")", ":", "nil", "memsize", "=", "rvalue_size", "if", "memsize", ">", "100_000_000_000", "result", "[", "obj", ".", "__id__", "]", "=", "MemoryProfiler", "::", "Stat", ".", "new", "(", "class_name", ",", "gem", ",", "file", ",", "location", ",", "memsize", ",", "string", ")", "rescue", "end", "end", "result", "end" ]
Iterates through objects in memory of a given generation. Stores results along with meta data of objects collected.
[ "Iterates", "through", "objects", "in", "memory", "of", "a", "given", "generation", ".", "Stores", "results", "along", "with", "meta", "data", "of", "objects", "collected", "." ]
bd87ff68559623d12c827800ee795475db4d5b8b
https://github.com/SamSaffron/memory_profiler/blob/bd87ff68559623d12c827800ee795475db4d5b8b/lib/memory_profiler/reporter.rb#L88-L129
train
SamSaffron/memory_profiler
lib/memory_profiler/results.rb
MemoryProfiler.Results.pretty_print
def pretty_print(io = $stdout, **options) # Handle the special case that Ruby PrettyPrint expects `pretty_print` # to be a customized pretty printing function for a class return io.pp_object(self) if defined?(PP) && io.is_a?(PP) io = File.open(options[:to_file], "w") if options[:to_file] color_output = options.fetch(:color_output) { io.respond_to?(:isatty) && io.isatty } @colorize = color_output ? Polychrome.new : Monochrome.new if options[:scale_bytes] total_allocated_output = scale_bytes(total_allocated_memsize) total_retained_output = scale_bytes(total_retained_memsize) else total_allocated_output = "#{total_allocated_memsize} bytes" total_retained_output = "#{total_retained_memsize} bytes" end io.puts "Total allocated: #{total_allocated_output} (#{total_allocated} objects)" io.puts "Total retained: #{total_retained_output} (#{total_retained} objects)" if options[:detailed_report] != false io.puts TYPES.each do |type| METRICS.each do |metric| NAMES.each do |name| scale_data = metric == "memory" && options[:scale_bytes] dump "#{type} #{metric} by #{name}", self.send("#{type}_#{metric}_by_#{name}"), io, scale_data end end end end io.puts dump_strings(io, "Allocated", strings_allocated, limit: options[:allocated_strings]) io.puts dump_strings(io, "Retained", strings_retained, limit: options[:retained_strings]) io.close if io.is_a? File end
ruby
def pretty_print(io = $stdout, **options) # Handle the special case that Ruby PrettyPrint expects `pretty_print` # to be a customized pretty printing function for a class return io.pp_object(self) if defined?(PP) && io.is_a?(PP) io = File.open(options[:to_file], "w") if options[:to_file] color_output = options.fetch(:color_output) { io.respond_to?(:isatty) && io.isatty } @colorize = color_output ? Polychrome.new : Monochrome.new if options[:scale_bytes] total_allocated_output = scale_bytes(total_allocated_memsize) total_retained_output = scale_bytes(total_retained_memsize) else total_allocated_output = "#{total_allocated_memsize} bytes" total_retained_output = "#{total_retained_memsize} bytes" end io.puts "Total allocated: #{total_allocated_output} (#{total_allocated} objects)" io.puts "Total retained: #{total_retained_output} (#{total_retained} objects)" if options[:detailed_report] != false io.puts TYPES.each do |type| METRICS.each do |metric| NAMES.each do |name| scale_data = metric == "memory" && options[:scale_bytes] dump "#{type} #{metric} by #{name}", self.send("#{type}_#{metric}_by_#{name}"), io, scale_data end end end end io.puts dump_strings(io, "Allocated", strings_allocated, limit: options[:allocated_strings]) io.puts dump_strings(io, "Retained", strings_retained, limit: options[:retained_strings]) io.close if io.is_a? File end
[ "def", "pretty_print", "(", "io", "=", "$stdout", ",", "**", "options", ")", "return", "io", ".", "pp_object", "(", "self", ")", "if", "defined?", "(", "PP", ")", "&&", "io", ".", "is_a?", "(", "PP", ")", "io", "=", "File", ".", "open", "(", "options", "[", ":to_file", "]", ",", "\"w\"", ")", "if", "options", "[", ":to_file", "]", "color_output", "=", "options", ".", "fetch", "(", ":color_output", ")", "{", "io", ".", "respond_to?", "(", ":isatty", ")", "&&", "io", ".", "isatty", "}", "@colorize", "=", "color_output", "?", "Polychrome", ".", "new", ":", "Monochrome", ".", "new", "if", "options", "[", ":scale_bytes", "]", "total_allocated_output", "=", "scale_bytes", "(", "total_allocated_memsize", ")", "total_retained_output", "=", "scale_bytes", "(", "total_retained_memsize", ")", "else", "total_allocated_output", "=", "\"#{total_allocated_memsize} bytes\"", "total_retained_output", "=", "\"#{total_retained_memsize} bytes\"", "end", "io", ".", "puts", "\"Total allocated: #{total_allocated_output} (#{total_allocated} objects)\"", "io", ".", "puts", "\"Total retained: #{total_retained_output} (#{total_retained} objects)\"", "if", "options", "[", ":detailed_report", "]", "!=", "false", "io", ".", "puts", "TYPES", ".", "each", "do", "|", "type", "|", "METRICS", ".", "each", "do", "|", "metric", "|", "NAMES", ".", "each", "do", "|", "name", "|", "scale_data", "=", "metric", "==", "\"memory\"", "&&", "options", "[", ":scale_bytes", "]", "dump", "\"#{type} #{metric} by #{name}\"", ",", "self", ".", "send", "(", "\"#{type}_#{metric}_by_#{name}\"", ")", ",", "io", ",", "scale_data", "end", "end", "end", "end", "io", ".", "puts", "dump_strings", "(", "io", ",", "\"Allocated\"", ",", "strings_allocated", ",", "limit", ":", "options", "[", ":allocated_strings", "]", ")", "io", ".", "puts", "dump_strings", "(", "io", ",", "\"Retained\"", ",", "strings_retained", ",", "limit", ":", "options", "[", ":retained_strings", "]", ")", "io", ".", "close", "if", "io", ".", "is_a?", "File", "end" ]
Output the results of the report @param [Hash] options the options for output @option opts [String] :to_file a path to your log file @option opts [Boolean] :color_output a flag for whether to colorize output @option opts [Integer] :retained_strings how many retained strings to print @option opts [Integer] :allocated_strings how many allocated strings to print @option opts [Boolean] :detailed_report should report include detailed information @option opts [Boolean] :scale_bytes calculates unit prefixes for the numbers of bytes
[ "Output", "the", "results", "of", "the", "report" ]
bd87ff68559623d12c827800ee795475db4d5b8b
https://github.com/SamSaffron/memory_profiler/blob/bd87ff68559623d12c827800ee795475db4d5b8b/lib/memory_profiler/results.rb#L107-L146
train
soundcloud/lhm
lib/lhm/chunker.rb
Lhm.Chunker.execute
def execute return unless @start && @limit @next_to_insert = @start while @next_to_insert <= @limit stride = @throttler.stride affected_rows = @connection.update(copy(bottom, top(stride))) if @throttler && affected_rows > 0 @throttler.run end @printer.notify(bottom, @limit) @next_to_insert = top(stride) + 1 break if @start == @limit end @printer.end end
ruby
def execute return unless @start && @limit @next_to_insert = @start while @next_to_insert <= @limit stride = @throttler.stride affected_rows = @connection.update(copy(bottom, top(stride))) if @throttler && affected_rows > 0 @throttler.run end @printer.notify(bottom, @limit) @next_to_insert = top(stride) + 1 break if @start == @limit end @printer.end end
[ "def", "execute", "return", "unless", "@start", "&&", "@limit", "@next_to_insert", "=", "@start", "while", "@next_to_insert", "<=", "@limit", "stride", "=", "@throttler", ".", "stride", "affected_rows", "=", "@connection", ".", "update", "(", "copy", "(", "bottom", ",", "top", "(", "stride", ")", ")", ")", "if", "@throttler", "&&", "affected_rows", ">", "0", "@throttler", ".", "run", "end", "@printer", ".", "notify", "(", "bottom", ",", "@limit", ")", "@next_to_insert", "=", "top", "(", "stride", ")", "+", "1", "break", "if", "@start", "==", "@limit", "end", "@printer", ".", "end", "end" ]
Copy from origin to destination in chunks of size `stride`. Use the `throttler` class to sleep between each stride.
[ "Copy", "from", "origin", "to", "destination", "in", "chunks", "of", "size", "stride", ".", "Use", "the", "throttler", "class", "to", "sleep", "between", "each", "stride", "." ]
50907121eee514649fa944fb300d5d8a64fa873e
https://github.com/soundcloud/lhm/blob/50907121eee514649fa944fb300d5d8a64fa873e/lib/lhm/chunker.rb#L27-L43
train
soundcloud/lhm
lib/lhm/migrator.rb
Lhm.Migrator.rename_column
def rename_column(old, nu) col = @origin.columns[old.to_s] definition = col[:type] definition += ' NOT NULL' unless col[:is_nullable] definition += " DEFAULT #{@connection.quote(col[:column_default])}" if col[:column_default] ddl('alter table `%s` change column `%s` `%s` %s' % [@name, old, nu, definition]) @renames[old.to_s] = nu.to_s end
ruby
def rename_column(old, nu) col = @origin.columns[old.to_s] definition = col[:type] definition += ' NOT NULL' unless col[:is_nullable] definition += " DEFAULT #{@connection.quote(col[:column_default])}" if col[:column_default] ddl('alter table `%s` change column `%s` `%s` %s' % [@name, old, nu, definition]) @renames[old.to_s] = nu.to_s end
[ "def", "rename_column", "(", "old", ",", "nu", ")", "col", "=", "@origin", ".", "columns", "[", "old", ".", "to_s", "]", "definition", "=", "col", "[", ":type", "]", "definition", "+=", "' NOT NULL'", "unless", "col", "[", ":is_nullable", "]", "definition", "+=", "\" DEFAULT #{@connection.quote(col[:column_default])}\"", "if", "col", "[", ":column_default", "]", "ddl", "(", "'alter table `%s` change column `%s` `%s` %s'", "%", "[", "@name", ",", "old", ",", "nu", ",", "definition", "]", ")", "@renames", "[", "old", ".", "to_s", "]", "=", "nu", ".", "to_s", "end" ]
Rename an existing column. @example Lhm.change_table(:users) do |m| m.rename_column(:login, :username) end @param [String] old Name of the column to change @param [String] nu New name to use for the column
[ "Rename", "an", "existing", "column", "." ]
50907121eee514649fa944fb300d5d8a64fa873e
https://github.com/soundcloud/lhm/blob/50907121eee514649fa944fb300d5d8a64fa873e/lib/lhm/migrator.rb#L83-L92
train
soundcloud/lhm
lib/lhm/migrator.rb
Lhm.Migrator.remove_index
def remove_index(columns, index_name = nil) columns = [columns].flatten.map(&:to_sym) from_origin = @origin.indices.find { |_, cols| cols.map(&:to_sym) == columns } index_name ||= from_origin[0] unless from_origin.nil? index_name ||= idx_name(@origin.name, columns) ddl('drop index `%s` on `%s`' % [index_name, @name]) end
ruby
def remove_index(columns, index_name = nil) columns = [columns].flatten.map(&:to_sym) from_origin = @origin.indices.find { |_, cols| cols.map(&:to_sym) == columns } index_name ||= from_origin[0] unless from_origin.nil? index_name ||= idx_name(@origin.name, columns) ddl('drop index `%s` on `%s`' % [index_name, @name]) end
[ "def", "remove_index", "(", "columns", ",", "index_name", "=", "nil", ")", "columns", "=", "[", "columns", "]", ".", "flatten", ".", "map", "(", "&", ":to_sym", ")", "from_origin", "=", "@origin", ".", "indices", ".", "find", "{", "|", "_", ",", "cols", "|", "cols", ".", "map", "(", "&", ":to_sym", ")", "==", "columns", "}", "index_name", "||=", "from_origin", "[", "0", "]", "unless", "from_origin", ".", "nil?", "index_name", "||=", "idx_name", "(", "@origin", ".", "name", ",", "columns", ")", "ddl", "(", "'drop index `%s` on `%s`'", "%", "[", "index_name", ",", "@name", "]", ")", "end" ]
Remove an index from a table @example Lhm.change_table(:users) do |m| m.remove_index(:comment) m.remove_index([:username, :created_at]) end @param [String, Symbol, Array<String, Symbol>] columns A column name given as String or Symbol. An Array of Strings or Symbols for compound indexes. @param [String, Symbol] index_name Optional name of the index to be removed
[ "Remove", "an", "index", "from", "a", "table" ]
50907121eee514649fa944fb300d5d8a64fa873e
https://github.com/soundcloud/lhm/blob/50907121eee514649fa944fb300d5d8a64fa873e/lib/lhm/migrator.rb#L159-L165
train
gocardless/hutch
lib/hutch/worker.rb
Hutch.Worker.setup_queues
def setup_queues logger.info 'setting up queues' vetted = @consumers.reject { |c| group_configured? && group_restricted?(c) } vetted.each do |c| setup_queue(c) end end
ruby
def setup_queues logger.info 'setting up queues' vetted = @consumers.reject { |c| group_configured? && group_restricted?(c) } vetted.each do |c| setup_queue(c) end end
[ "def", "setup_queues", "logger", ".", "info", "'setting up queues'", "vetted", "=", "@consumers", ".", "reject", "{", "|", "c", "|", "group_configured?", "&&", "group_restricted?", "(", "c", ")", "}", "vetted", ".", "each", "do", "|", "c", "|", "setup_queue", "(", "c", ")", "end", "end" ]
Set up the queues for each of the worker's consumers.
[ "Set", "up", "the", "queues", "for", "each", "of", "the", "worker", "s", "consumers", "." ]
9314b3b8c84abeb78170730757f3eb8ccc4f54c5
https://github.com/gocardless/hutch/blob/9314b3b8c84abeb78170730757f3eb8ccc4f54c5/lib/hutch/worker.rb#L37-L43
train
gocardless/hutch
lib/hutch/worker.rb
Hutch.Worker.setup_queue
def setup_queue(consumer) logger.info "setting up queue: #{consumer.get_queue_name}" queue = @broker.queue(consumer.get_queue_name, consumer.get_arguments) @broker.bind_queue(queue, consumer.routing_keys) queue.subscribe(consumer_tag: unique_consumer_tag, manual_ack: true) do |*args| delivery_info, properties, payload = Hutch::Adapter.decode_message(*args) handle_message(consumer, delivery_info, properties, payload) end end
ruby
def setup_queue(consumer) logger.info "setting up queue: #{consumer.get_queue_name}" queue = @broker.queue(consumer.get_queue_name, consumer.get_arguments) @broker.bind_queue(queue, consumer.routing_keys) queue.subscribe(consumer_tag: unique_consumer_tag, manual_ack: true) do |*args| delivery_info, properties, payload = Hutch::Adapter.decode_message(*args) handle_message(consumer, delivery_info, properties, payload) end end
[ "def", "setup_queue", "(", "consumer", ")", "logger", ".", "info", "\"setting up queue: #{consumer.get_queue_name}\"", "queue", "=", "@broker", ".", "queue", "(", "consumer", ".", "get_queue_name", ",", "consumer", ".", "get_arguments", ")", "@broker", ".", "bind_queue", "(", "queue", ",", "consumer", ".", "routing_keys", ")", "queue", ".", "subscribe", "(", "consumer_tag", ":", "unique_consumer_tag", ",", "manual_ack", ":", "true", ")", "do", "|", "*", "args", "|", "delivery_info", ",", "properties", ",", "payload", "=", "Hutch", "::", "Adapter", ".", "decode_message", "(", "*", "args", ")", "handle_message", "(", "consumer", ",", "delivery_info", ",", "properties", ",", "payload", ")", "end", "end" ]
Bind a consumer's routing keys to its queue, and set up a subscription to receive messages sent to the queue.
[ "Bind", "a", "consumer", "s", "routing", "keys", "to", "its", "queue", "and", "set", "up", "a", "subscription", "to", "receive", "messages", "sent", "to", "the", "queue", "." ]
9314b3b8c84abeb78170730757f3eb8ccc4f54c5
https://github.com/gocardless/hutch/blob/9314b3b8c84abeb78170730757f3eb8ccc4f54c5/lib/hutch/worker.rb#L47-L57
train
gocardless/hutch
lib/hutch/worker.rb
Hutch.Worker.handle_message
def handle_message(consumer, delivery_info, properties, payload) serializer = consumer.get_serializer || Hutch::Config[:serializer] logger.debug { spec = serializer.binary? ? "#{payload.bytesize} bytes" : "#{payload}" "message(#{properties.message_id || '-'}): " + "routing key: #{delivery_info.routing_key}, " + "consumer: #{consumer}, " + "payload: #{spec}" } message = Message.new(delivery_info, properties, payload, serializer) consumer_instance = consumer.new.tap { |c| c.broker, c.delivery_info = @broker, delivery_info } with_tracing(consumer_instance).handle(message) @broker.ack(delivery_info.delivery_tag) rescue => ex acknowledge_error(delivery_info, properties, @broker, ex) handle_error(properties, payload, consumer, ex) end
ruby
def handle_message(consumer, delivery_info, properties, payload) serializer = consumer.get_serializer || Hutch::Config[:serializer] logger.debug { spec = serializer.binary? ? "#{payload.bytesize} bytes" : "#{payload}" "message(#{properties.message_id || '-'}): " + "routing key: #{delivery_info.routing_key}, " + "consumer: #{consumer}, " + "payload: #{spec}" } message = Message.new(delivery_info, properties, payload, serializer) consumer_instance = consumer.new.tap { |c| c.broker, c.delivery_info = @broker, delivery_info } with_tracing(consumer_instance).handle(message) @broker.ack(delivery_info.delivery_tag) rescue => ex acknowledge_error(delivery_info, properties, @broker, ex) handle_error(properties, payload, consumer, ex) end
[ "def", "handle_message", "(", "consumer", ",", "delivery_info", ",", "properties", ",", "payload", ")", "serializer", "=", "consumer", ".", "get_serializer", "||", "Hutch", "::", "Config", "[", ":serializer", "]", "logger", ".", "debug", "{", "spec", "=", "serializer", ".", "binary?", "?", "\"#{payload.bytesize} bytes\"", ":", "\"#{payload}\"", "\"message(#{properties.message_id || '-'}): \"", "+", "\"routing key: #{delivery_info.routing_key}, \"", "+", "\"consumer: #{consumer}, \"", "+", "\"payload: #{spec}\"", "}", "message", "=", "Message", ".", "new", "(", "delivery_info", ",", "properties", ",", "payload", ",", "serializer", ")", "consumer_instance", "=", "consumer", ".", "new", ".", "tap", "{", "|", "c", "|", "c", ".", "broker", ",", "c", ".", "delivery_info", "=", "@broker", ",", "delivery_info", "}", "with_tracing", "(", "consumer_instance", ")", ".", "handle", "(", "message", ")", "@broker", ".", "ack", "(", "delivery_info", ".", "delivery_tag", ")", "rescue", "=>", "ex", "acknowledge_error", "(", "delivery_info", ",", "properties", ",", "@broker", ",", "ex", ")", "handle_error", "(", "properties", ",", "payload", ",", "consumer", ",", "ex", ")", "end" ]
Called internally when a new messages comes in from RabbitMQ. Responsible for wrapping up the message and passing it to the consumer.
[ "Called", "internally", "when", "a", "new", "messages", "comes", "in", "from", "RabbitMQ", ".", "Responsible", "for", "wrapping", "up", "the", "message", "and", "passing", "it", "to", "the", "consumer", "." ]
9314b3b8c84abeb78170730757f3eb8ccc4f54c5
https://github.com/gocardless/hutch/blob/9314b3b8c84abeb78170730757f3eb8ccc4f54c5/lib/hutch/worker.rb#L61-L78
train
gocardless/hutch
lib/hutch/broker.rb
Hutch.Broker.set_up_api_connection
def set_up_api_connection logger.info "connecting to rabbitmq HTTP API (#{api_config.sanitized_uri})" with_authentication_error_handler do with_connection_error_handler do @api_client = CarrotTop.new(host: api_config.host, port: api_config.port, user: api_config.username, password: api_config.password, ssl: api_config.ssl) @api_client.exchanges end end end
ruby
def set_up_api_connection logger.info "connecting to rabbitmq HTTP API (#{api_config.sanitized_uri})" with_authentication_error_handler do with_connection_error_handler do @api_client = CarrotTop.new(host: api_config.host, port: api_config.port, user: api_config.username, password: api_config.password, ssl: api_config.ssl) @api_client.exchanges end end end
[ "def", "set_up_api_connection", "logger", ".", "info", "\"connecting to rabbitmq HTTP API (#{api_config.sanitized_uri})\"", "with_authentication_error_handler", "do", "with_connection_error_handler", "do", "@api_client", "=", "CarrotTop", ".", "new", "(", "host", ":", "api_config", ".", "host", ",", "port", ":", "api_config", ".", "port", ",", "user", ":", "api_config", ".", "username", ",", "password", ":", "api_config", ".", "password", ",", "ssl", ":", "api_config", ".", "ssl", ")", "@api_client", ".", "exchanges", "end", "end", "end" ]
Set up the connection to the RabbitMQ management API. Unfortunately, this is necessary to do a few things that are impossible over AMQP. E.g. listing queues and bindings.
[ "Set", "up", "the", "connection", "to", "the", "RabbitMQ", "management", "API", ".", "Unfortunately", "this", "is", "necessary", "to", "do", "a", "few", "things", "that", "are", "impossible", "over", "AMQP", ".", "E", ".", "g", ".", "listing", "queues", "and", "bindings", "." ]
9314b3b8c84abeb78170730757f3eb8ccc4f54c5
https://github.com/gocardless/hutch/blob/9314b3b8c84abeb78170730757f3eb8ccc4f54c5/lib/hutch/broker.rb#L144-L155
train
gocardless/hutch
lib/hutch/broker.rb
Hutch.Broker.bindings
def bindings results = Hash.new { |hash, key| hash[key] = [] } api_client.bindings.each do |binding| next if binding['destination'] == binding['routing_key'] next unless binding['source'] == @config[:mq_exchange] next unless binding['vhost'] == @config[:mq_vhost] results[binding['destination']] << binding['routing_key'] end results end
ruby
def bindings results = Hash.new { |hash, key| hash[key] = [] } api_client.bindings.each do |binding| next if binding['destination'] == binding['routing_key'] next unless binding['source'] == @config[:mq_exchange] next unless binding['vhost'] == @config[:mq_vhost] results[binding['destination']] << binding['routing_key'] end results end
[ "def", "bindings", "results", "=", "Hash", ".", "new", "{", "|", "hash", ",", "key", "|", "hash", "[", "key", "]", "=", "[", "]", "}", "api_client", ".", "bindings", ".", "each", "do", "|", "binding", "|", "next", "if", "binding", "[", "'destination'", "]", "==", "binding", "[", "'routing_key'", "]", "next", "unless", "binding", "[", "'source'", "]", "==", "@config", "[", ":mq_exchange", "]", "next", "unless", "binding", "[", "'vhost'", "]", "==", "@config", "[", ":mq_vhost", "]", "results", "[", "binding", "[", "'destination'", "]", "]", "<<", "binding", "[", "'routing_key'", "]", "end", "results", "end" ]
Return a mapping of queue names to the routing keys they're bound to.
[ "Return", "a", "mapping", "of", "queue", "names", "to", "the", "routing", "keys", "they", "re", "bound", "to", "." ]
9314b3b8c84abeb78170730757f3eb8ccc4f54c5
https://github.com/gocardless/hutch/blob/9314b3b8c84abeb78170730757f3eb8ccc4f54c5/lib/hutch/broker.rb#L182-L191
train
gocardless/hutch
lib/hutch/broker.rb
Hutch.Broker.unbind_redundant_bindings
def unbind_redundant_bindings(queue, routing_keys) return unless http_api_use_enabled? bindings.each do |dest, keys| next unless dest == queue.name keys.reject { |key| routing_keys.include?(key) }.each do |key| logger.debug "removing redundant binding #{queue.name} <--> #{key}" queue.unbind(exchange, routing_key: key) end end end
ruby
def unbind_redundant_bindings(queue, routing_keys) return unless http_api_use_enabled? bindings.each do |dest, keys| next unless dest == queue.name keys.reject { |key| routing_keys.include?(key) }.each do |key| logger.debug "removing redundant binding #{queue.name} <--> #{key}" queue.unbind(exchange, routing_key: key) end end end
[ "def", "unbind_redundant_bindings", "(", "queue", ",", "routing_keys", ")", "return", "unless", "http_api_use_enabled?", "bindings", ".", "each", "do", "|", "dest", ",", "keys", "|", "next", "unless", "dest", "==", "queue", ".", "name", "keys", ".", "reject", "{", "|", "key", "|", "routing_keys", ".", "include?", "(", "key", ")", "}", ".", "each", "do", "|", "key", "|", "logger", ".", "debug", "\"removing redundant binding #{queue.name} <", "queue", ".", "unbind", "(", "exchange", ",", "routing_key", ":", "key", ")", "end", "end", "end" ]
Find the existing bindings, and unbind any redundant bindings
[ "Find", "the", "existing", "bindings", "and", "unbind", "any", "redundant", "bindings" ]
9314b3b8c84abeb78170730757f3eb8ccc4f54c5
https://github.com/gocardless/hutch/blob/9314b3b8c84abeb78170730757f3eb8ccc4f54c5/lib/hutch/broker.rb#L194-L204
train
gocardless/hutch
lib/hutch/broker.rb
Hutch.Broker.bind_queue
def bind_queue(queue, routing_keys) unbind_redundant_bindings(queue, routing_keys) # Ensure all the desired bindings are present routing_keys.each do |routing_key| logger.debug "creating binding #{queue.name} <--> #{routing_key}" queue.bind(exchange, routing_key: routing_key) end end
ruby
def bind_queue(queue, routing_keys) unbind_redundant_bindings(queue, routing_keys) # Ensure all the desired bindings are present routing_keys.each do |routing_key| logger.debug "creating binding #{queue.name} <--> #{routing_key}" queue.bind(exchange, routing_key: routing_key) end end
[ "def", "bind_queue", "(", "queue", ",", "routing_keys", ")", "unbind_redundant_bindings", "(", "queue", ",", "routing_keys", ")", "routing_keys", ".", "each", "do", "|", "routing_key", "|", "logger", ".", "debug", "\"creating binding #{queue.name} <", "queue", ".", "bind", "(", "exchange", ",", "routing_key", ":", "routing_key", ")", "end", "end" ]
Bind a queue to the broker's exchange on the routing keys provided. Any existing bindings on the queue that aren't present in the array of routing keys will be unbound.
[ "Bind", "a", "queue", "to", "the", "broker", "s", "exchange", "on", "the", "routing", "keys", "provided", ".", "Any", "existing", "bindings", "on", "the", "queue", "that", "aren", "t", "present", "in", "the", "array", "of", "routing", "keys", "will", "be", "unbound", "." ]
9314b3b8c84abeb78170730757f3eb8ccc4f54c5
https://github.com/gocardless/hutch/blob/9314b3b8c84abeb78170730757f3eb8ccc4f54c5/lib/hutch/broker.rb#L209-L217
train
gocardless/hutch
lib/hutch/cli.rb
Hutch.CLI.run
def run(argv = ARGV) Hutch::Config.initialize parse_options(argv) daemonise_process write_pid if Hutch::Config.pidfile Hutch.logger.info "hutch booted with pid #{::Process.pid}" if load_app && start_work_loop == :success # If we got here, the worker was shut down nicely Hutch.logger.info 'hutch shut down gracefully' exit 0 else Hutch.logger.info 'hutch terminated due to an error' exit 1 end end
ruby
def run(argv = ARGV) Hutch::Config.initialize parse_options(argv) daemonise_process write_pid if Hutch::Config.pidfile Hutch.logger.info "hutch booted with pid #{::Process.pid}" if load_app && start_work_loop == :success # If we got here, the worker was shut down nicely Hutch.logger.info 'hutch shut down gracefully' exit 0 else Hutch.logger.info 'hutch terminated due to an error' exit 1 end end
[ "def", "run", "(", "argv", "=", "ARGV", ")", "Hutch", "::", "Config", ".", "initialize", "parse_options", "(", "argv", ")", "daemonise_process", "write_pid", "if", "Hutch", "::", "Config", ".", "pidfile", "Hutch", ".", "logger", ".", "info", "\"hutch booted with pid #{::Process.pid}\"", "if", "load_app", "&&", "start_work_loop", "==", ":success", "Hutch", ".", "logger", ".", "info", "'hutch shut down gracefully'", "exit", "0", "else", "Hutch", ".", "logger", ".", "info", "'hutch terminated due to an error'", "exit", "1", "end", "end" ]
Run a Hutch worker with the command line interface.
[ "Run", "a", "Hutch", "worker", "with", "the", "command", "line", "interface", "." ]
9314b3b8c84abeb78170730757f3eb8ccc4f54c5
https://github.com/gocardless/hutch/blob/9314b3b8c84abeb78170730757f3eb8ccc4f54c5/lib/hutch/cli.rb#L13-L31
train
geokit/geokit
lib/geokit/bounds.rb
Geokit.Bounds.contains?
def contains?(point) point = Geokit::LatLng.normalize(point) res = point.lat > @sw.lat && point.lat < @ne.lat if crosses_meridian? res &= point.lng < @ne.lng || point.lng > @sw.lng else res &= point.lng < @ne.lng && point.lng > @sw.lng end res end
ruby
def contains?(point) point = Geokit::LatLng.normalize(point) res = point.lat > @sw.lat && point.lat < @ne.lat if crosses_meridian? res &= point.lng < @ne.lng || point.lng > @sw.lng else res &= point.lng < @ne.lng && point.lng > @sw.lng end res end
[ "def", "contains?", "(", "point", ")", "point", "=", "Geokit", "::", "LatLng", ".", "normalize", "(", "point", ")", "res", "=", "point", ".", "lat", ">", "@sw", ".", "lat", "&&", "point", ".", "lat", "<", "@ne", ".", "lat", "if", "crosses_meridian?", "res", "&=", "point", ".", "lng", "<", "@ne", ".", "lng", "||", "point", ".", "lng", ">", "@sw", ".", "lng", "else", "res", "&=", "point", ".", "lng", "<", "@ne", ".", "lng", "&&", "point", ".", "lng", ">", "@sw", ".", "lng", "end", "res", "end" ]
Returns true if the bounds contain the passed point. allows for bounds which cross the meridian
[ "Returns", "true", "if", "the", "bounds", "contain", "the", "passed", "point", ".", "allows", "for", "bounds", "which", "cross", "the", "meridian" ]
b7c13376bd85bf14f9534228ea466d09ac0afbf4
https://github.com/geokit/geokit/blob/b7c13376bd85bf14f9534228ea466d09ac0afbf4/lib/geokit/bounds.rb#L32-L41
train
geokit/geokit
lib/geokit/geo_loc.rb
Geokit.GeoLoc.to_geocodeable_s
def to_geocodeable_s a = [street_address, district, city, state, zip, country_code].compact a.delete_if { |e| !e || e == '' } a.join(', ') end
ruby
def to_geocodeable_s a = [street_address, district, city, state, zip, country_code].compact a.delete_if { |e| !e || e == '' } a.join(', ') end
[ "def", "to_geocodeable_s", "a", "=", "[", "street_address", ",", "district", ",", "city", ",", "state", ",", "zip", ",", "country_code", "]", ".", "compact", "a", ".", "delete_if", "{", "|", "e", "|", "!", "e", "||", "e", "==", "''", "}", "a", ".", "join", "(", "', '", ")", "end" ]
Returns a comma-delimited string consisting of the street address, city, state, zip, and country code. Only includes those attributes that are non-blank.
[ "Returns", "a", "comma", "-", "delimited", "string", "consisting", "of", "the", "street", "address", "city", "state", "zip", "and", "country", "code", ".", "Only", "includes", "those", "attributes", "that", "are", "non", "-", "blank", "." ]
b7c13376bd85bf14f9534228ea466d09ac0afbf4
https://github.com/geokit/geokit/blob/b7c13376bd85bf14f9534228ea466d09ac0afbf4/lib/geokit/geo_loc.rb#L138-L142
train
ClosureTree/closure_tree
lib/closure_tree/hash_tree_support.rb
ClosureTree.HashTreeSupport.build_hash_tree
def build_hash_tree(tree_scope) tree = ActiveSupport::OrderedHash.new id_to_hash = {} tree_scope.each do |ea| h = id_to_hash[ea.id] = ActiveSupport::OrderedHash.new (id_to_hash[ea._ct_parent_id] || tree)[ea] = h end tree end
ruby
def build_hash_tree(tree_scope) tree = ActiveSupport::OrderedHash.new id_to_hash = {} tree_scope.each do |ea| h = id_to_hash[ea.id] = ActiveSupport::OrderedHash.new (id_to_hash[ea._ct_parent_id] || tree)[ea] = h end tree end
[ "def", "build_hash_tree", "(", "tree_scope", ")", "tree", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "id_to_hash", "=", "{", "}", "tree_scope", ".", "each", "do", "|", "ea", "|", "h", "=", "id_to_hash", "[", "ea", ".", "id", "]", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "(", "id_to_hash", "[", "ea", ".", "_ct_parent_id", "]", "||", "tree", ")", "[", "ea", "]", "=", "h", "end", "tree", "end" ]
Builds nested hash structure using the scope returned from the passed in scope
[ "Builds", "nested", "hash", "structure", "using", "the", "scope", "returned", "from", "the", "passed", "in", "scope" ]
9babda807861a1b76745cfb986b001db01017ef9
https://github.com/ClosureTree/closure_tree/blob/9babda807861a1b76745cfb986b001db01017ef9/lib/closure_tree/hash_tree_support.rb#L25-L34
train
ClosureTree/closure_tree
lib/closure_tree/finders.rb
ClosureTree.Finders.find_or_create_by_path
def find_or_create_by_path(path, attributes = {}) subpath = _ct.build_ancestry_attr_path(path, attributes) return self if subpath.empty? found = find_by_path(subpath, attributes) return found if found attrs = subpath.shift _ct.with_advisory_lock do # shenanigans because children.create is bound to the superclass # (in the case of polymorphism): child = self.children.where(attrs).first || begin # Support STI creation by using base_class: _ct.create(self.class, attrs).tap do |ea| # We know that there isn't a cycle, because we just created it, and # cycle detection is expensive when the node is deep. ea._ct_skip_cycle_detection! self.children << ea end end child.find_or_create_by_path(subpath, attributes) end end
ruby
def find_or_create_by_path(path, attributes = {}) subpath = _ct.build_ancestry_attr_path(path, attributes) return self if subpath.empty? found = find_by_path(subpath, attributes) return found if found attrs = subpath.shift _ct.with_advisory_lock do # shenanigans because children.create is bound to the superclass # (in the case of polymorphism): child = self.children.where(attrs).first || begin # Support STI creation by using base_class: _ct.create(self.class, attrs).tap do |ea| # We know that there isn't a cycle, because we just created it, and # cycle detection is expensive when the node is deep. ea._ct_skip_cycle_detection! self.children << ea end end child.find_or_create_by_path(subpath, attributes) end end
[ "def", "find_or_create_by_path", "(", "path", ",", "attributes", "=", "{", "}", ")", "subpath", "=", "_ct", ".", "build_ancestry_attr_path", "(", "path", ",", "attributes", ")", "return", "self", "if", "subpath", ".", "empty?", "found", "=", "find_by_path", "(", "subpath", ",", "attributes", ")", "return", "found", "if", "found", "attrs", "=", "subpath", ".", "shift", "_ct", ".", "with_advisory_lock", "do", "child", "=", "self", ".", "children", ".", "where", "(", "attrs", ")", ".", "first", "||", "begin", "_ct", ".", "create", "(", "self", ".", "class", ",", "attrs", ")", ".", "tap", "do", "|", "ea", "|", "ea", ".", "_ct_skip_cycle_detection!", "self", ".", "children", "<<", "ea", "end", "end", "child", ".", "find_or_create_by_path", "(", "subpath", ",", "attributes", ")", "end", "end" ]
Find or create a descendant node whose +ancestry_path+ will be ```self.ancestry_path + path```
[ "Find", "or", "create", "a", "descendant", "node", "whose", "+", "ancestry_path", "+", "will", "be", "self", ".", "ancestry_path", "+", "path" ]
9babda807861a1b76745cfb986b001db01017ef9
https://github.com/ClosureTree/closure_tree/blob/9babda807861a1b76745cfb986b001db01017ef9/lib/closure_tree/finders.rb#L12-L34
train
samvera/hyrax
app/helpers/hyrax/hyrax_helper_behavior.rb
Hyrax.HyraxHelperBehavior.iconify_auto_link
def iconify_auto_link(field, show_link = true) if field.is_a? Hash options = field[:config].separator_options || {} text = field[:value].to_sentence(options) else text = field end # this block is only executed when a link is inserted; # if we pass text containing no links, it just returns text. auto_link(html_escape(text)) do |value| "<span class='glyphicon glyphicon-new-window'></span>#{('&nbsp;' + value) if show_link}" end end
ruby
def iconify_auto_link(field, show_link = true) if field.is_a? Hash options = field[:config].separator_options || {} text = field[:value].to_sentence(options) else text = field end # this block is only executed when a link is inserted; # if we pass text containing no links, it just returns text. auto_link(html_escape(text)) do |value| "<span class='glyphicon glyphicon-new-window'></span>#{('&nbsp;' + value) if show_link}" end end
[ "def", "iconify_auto_link", "(", "field", ",", "show_link", "=", "true", ")", "if", "field", ".", "is_a?", "Hash", "options", "=", "field", "[", ":config", "]", ".", "separator_options", "||", "{", "}", "text", "=", "field", "[", ":value", "]", ".", "to_sentence", "(", "options", ")", "else", "text", "=", "field", "end", "auto_link", "(", "html_escape", "(", "text", ")", ")", "do", "|", "value", "|", "\"<span class='glyphicon glyphicon-new-window'></span>#{('&nbsp;' + value) if show_link}\"", "end", "end" ]
Uses Rails auto_link to add links to fields @param field [String,Hash] string to format and escape, or a hash as per helper_method @option field [SolrDocument] :document @option field [String] :field name of the solr field @option field [Blacklight::Configuration::IndexField, Blacklight::Configuration::ShowField] :config @option field [Array] :value array of values for the field @param show_link [Boolean] @return [ActiveSupport::SafeBuffer] @todo stop being a helper_method, start being part of the Blacklight render stack?
[ "Uses", "Rails", "auto_link", "to", "add", "links", "to", "fields" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/helpers/hyrax/hyrax_helper_behavior.rb#L171-L183
train
samvera/hyrax
app/services/hyrax/user_stat_importer.rb
Hyrax.UserStatImporter.sorted_users
def sorted_users users = [] ::User.find_each do |user| users.push(UserRecord.new(user.id, user.user_key, date_since_last_cache(user))) end users.sort_by(&:last_stats_update) end
ruby
def sorted_users users = [] ::User.find_each do |user| users.push(UserRecord.new(user.id, user.user_key, date_since_last_cache(user))) end users.sort_by(&:last_stats_update) end
[ "def", "sorted_users", "users", "=", "[", "]", "::", "User", ".", "find_each", "do", "|", "user", "|", "users", ".", "push", "(", "UserRecord", ".", "new", "(", "user", ".", "id", ",", "user", ".", "user_key", ",", "date_since_last_cache", "(", "user", ")", ")", ")", "end", "users", ".", "sort_by", "(", "&", ":last_stats_update", ")", "end" ]
Returns an array of users sorted by the date of their last stats update. Users that have not been recently updated will be at the top of the array.
[ "Returns", "an", "array", "of", "users", "sorted", "by", "the", "date", "of", "their", "last", "stats", "update", ".", "Users", "that", "have", "not", "been", "recently", "updated", "will", "be", "at", "the", "top", "of", "the", "array", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/user_stat_importer.rb#L39-L45
train
samvera/hyrax
app/services/hyrax/user_stat_importer.rb
Hyrax.UserStatImporter.rescue_and_retry
def rescue_and_retry(fail_message) Retriable.retriable(retry_options) do return yield end rescue StandardError => exception log_message fail_message log_message "Last exception #{exception}" end
ruby
def rescue_and_retry(fail_message) Retriable.retriable(retry_options) do return yield end rescue StandardError => exception log_message fail_message log_message "Last exception #{exception}" end
[ "def", "rescue_and_retry", "(", "fail_message", ")", "Retriable", ".", "retriable", "(", "retry_options", ")", "do", "return", "yield", "end", "rescue", "StandardError", "=>", "exception", "log_message", "fail_message", "log_message", "\"Last exception #{exception}\"", "end" ]
This method never fails. It tries multiple times and finally logs the exception
[ "This", "method", "never", "fails", ".", "It", "tries", "multiple", "times", "and", "finally", "logs", "the", "exception" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/user_stat_importer.rb#L79-L86
train
samvera/hyrax
app/controllers/concerns/hyrax/leases_controller_behavior.rb
Hyrax.LeasesControllerBehavior.destroy
def destroy Hyrax::Actors::LeaseActor.new(curation_concern).destroy flash[:notice] = curation_concern.lease_history.last if curation_concern.work? && curation_concern.file_sets.present? redirect_to confirm_permission_path else redirect_to edit_lease_path end end
ruby
def destroy Hyrax::Actors::LeaseActor.new(curation_concern).destroy flash[:notice] = curation_concern.lease_history.last if curation_concern.work? && curation_concern.file_sets.present? redirect_to confirm_permission_path else redirect_to edit_lease_path end end
[ "def", "destroy", "Hyrax", "::", "Actors", "::", "LeaseActor", ".", "new", "(", "curation_concern", ")", ".", "destroy", "flash", "[", ":notice", "]", "=", "curation_concern", ".", "lease_history", ".", "last", "if", "curation_concern", ".", "work?", "&&", "curation_concern", ".", "file_sets", ".", "present?", "redirect_to", "confirm_permission_path", "else", "redirect_to", "edit_lease_path", "end", "end" ]
Removes a single lease
[ "Removes", "a", "single", "lease" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/concerns/hyrax/leases_controller_behavior.rb#L15-L23
train
samvera/hyrax
app/models/concerns/hyrax/collection_behavior.rb
Hyrax.CollectionBehavior.bytes
def bytes return 0 if member_object_ids.empty? raise "Collection must be saved to query for bytes" if new_record? # One query per member_id because Solr is not a relational database member_object_ids.collect { |work_id| size_for_work(work_id) }.sum end
ruby
def bytes return 0 if member_object_ids.empty? raise "Collection must be saved to query for bytes" if new_record? # One query per member_id because Solr is not a relational database member_object_ids.collect { |work_id| size_for_work(work_id) }.sum end
[ "def", "bytes", "return", "0", "if", "member_object_ids", ".", "empty?", "raise", "\"Collection must be saved to query for bytes\"", "if", "new_record?", "member_object_ids", ".", "collect", "{", "|", "work_id", "|", "size_for_work", "(", "work_id", ")", "}", ".", "sum", "end" ]
Compute the sum of each file in the collection using Solr to avoid having to access Fedora @return [Fixnum] size of collection in bytes @raise [RuntimeError] unsaved record does not exist in solr
[ "Compute", "the", "sum", "of", "each", "file", "in", "the", "collection", "using", "Solr", "to", "avoid", "having", "to", "access", "Fedora" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/concerns/hyrax/collection_behavior.rb#L118-L125
train
samvera/hyrax
app/models/concerns/hyrax/collection_behavior.rb
Hyrax.CollectionBehavior.size_for_work
def size_for_work(work_id) argz = { fl: "id, #{file_size_field}", fq: "{!join from=#{member_ids_field} to=id}id:#{work_id}" } files = ::FileSet.search_with_conditions({}, argz) files.reduce(0) { |sum, f| sum + f[file_size_field].to_i } end
ruby
def size_for_work(work_id) argz = { fl: "id, #{file_size_field}", fq: "{!join from=#{member_ids_field} to=id}id:#{work_id}" } files = ::FileSet.search_with_conditions({}, argz) files.reduce(0) { |sum, f| sum + f[file_size_field].to_i } end
[ "def", "size_for_work", "(", "work_id", ")", "argz", "=", "{", "fl", ":", "\"id, #{file_size_field}\"", ",", "fq", ":", "\"{!join from=#{member_ids_field} to=id}id:#{work_id}\"", "}", "files", "=", "::", "FileSet", ".", "search_with_conditions", "(", "{", "}", ",", "argz", ")", "files", ".", "reduce", "(", "0", ")", "{", "|", "sum", ",", "f", "|", "sum", "+", "f", "[", "file_size_field", "]", ".", "to_i", "}", "end" ]
Calculate the size of all the files in the work @param work_id [String] identifer for a work @return [Integer] the size in bytes
[ "Calculate", "the", "size", "of", "all", "the", "files", "in", "the", "work" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/concerns/hyrax/collection_behavior.rb#L174-L179
train
samvera/hyrax
app/services/hyrax/admin_set_service.rb
Hyrax.AdminSetService.search_results_with_work_count
def search_results_with_work_count(access, join_field: "isPartOf_ssim") admin_sets = search_results(access) ids = admin_sets.map(&:id).join(',') query = "{!terms f=#{join_field}}#{ids}" results = ActiveFedora::SolrService.instance.conn.get( ActiveFedora::SolrService.select_path, params: { fq: query, rows: 0, 'facet.field' => join_field } ) counts = results['facet_counts']['facet_fields'][join_field].each_slice(2).to_h file_counts = count_files(admin_sets) admin_sets.map do |admin_set| SearchResultForWorkCount.new(admin_set, counts[admin_set.id].to_i, file_counts[admin_set.id].to_i) end end
ruby
def search_results_with_work_count(access, join_field: "isPartOf_ssim") admin_sets = search_results(access) ids = admin_sets.map(&:id).join(',') query = "{!terms f=#{join_field}}#{ids}" results = ActiveFedora::SolrService.instance.conn.get( ActiveFedora::SolrService.select_path, params: { fq: query, rows: 0, 'facet.field' => join_field } ) counts = results['facet_counts']['facet_fields'][join_field].each_slice(2).to_h file_counts = count_files(admin_sets) admin_sets.map do |admin_set| SearchResultForWorkCount.new(admin_set, counts[admin_set.id].to_i, file_counts[admin_set.id].to_i) end end
[ "def", "search_results_with_work_count", "(", "access", ",", "join_field", ":", "\"isPartOf_ssim\"", ")", "admin_sets", "=", "search_results", "(", "access", ")", "ids", "=", "admin_sets", ".", "map", "(", "&", ":id", ")", ".", "join", "(", "','", ")", "query", "=", "\"{!terms f=#{join_field}}#{ids}\"", "results", "=", "ActiveFedora", "::", "SolrService", ".", "instance", ".", "conn", ".", "get", "(", "ActiveFedora", "::", "SolrService", ".", "select_path", ",", "params", ":", "{", "fq", ":", "query", ",", "rows", ":", "0", ",", "'facet.field'", "=>", "join_field", "}", ")", "counts", "=", "results", "[", "'facet_counts'", "]", "[", "'facet_fields'", "]", "[", "join_field", "]", ".", "each_slice", "(", "2", ")", ".", "to_h", "file_counts", "=", "count_files", "(", "admin_sets", ")", "admin_sets", ".", "map", "do", "|", "admin_set", "|", "SearchResultForWorkCount", ".", "new", "(", "admin_set", ",", "counts", "[", "admin_set", ".", "id", "]", ".", "to_i", ",", "file_counts", "[", "admin_set", ".", "id", "]", ".", "to_i", ")", "end", "end" ]
This performs a two pass query, first getting the AdminSets and then getting the work and file counts @param [Symbol] access :read or :edit @param join_field [String] how are we joining the admin_set ids (by default "isPartOf_ssim") @return [Array<Hyrax::AdminSetService::SearchResultForWorkCount>] a list with document, then work and file count
[ "This", "performs", "a", "two", "pass", "query", "first", "getting", "the", "AdminSets", "and", "then", "getting", "the", "work", "and", "file", "counts" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/admin_set_service.rb#L29-L44
train
samvera/hyrax
app/services/hyrax/admin_set_service.rb
Hyrax.AdminSetService.count_files
def count_files(admin_sets) file_counts = Hash.new(0) admin_sets.each do |admin_set| query = "{!join from=file_set_ids_ssim to=id}isPartOf_ssim:#{admin_set.id}" file_results = ActiveFedora::SolrService.instance.conn.get( ActiveFedora::SolrService.select_path, params: { fq: [query, "has_model_ssim:FileSet"], rows: 0 } ) file_counts[admin_set.id] = file_results['response']['numFound'] end file_counts end
ruby
def count_files(admin_sets) file_counts = Hash.new(0) admin_sets.each do |admin_set| query = "{!join from=file_set_ids_ssim to=id}isPartOf_ssim:#{admin_set.id}" file_results = ActiveFedora::SolrService.instance.conn.get( ActiveFedora::SolrService.select_path, params: { fq: [query, "has_model_ssim:FileSet"], rows: 0 } ) file_counts[admin_set.id] = file_results['response']['numFound'] end file_counts end
[ "def", "count_files", "(", "admin_sets", ")", "file_counts", "=", "Hash", ".", "new", "(", "0", ")", "admin_sets", ".", "each", "do", "|", "admin_set", "|", "query", "=", "\"{!join from=file_set_ids_ssim to=id}isPartOf_ssim:#{admin_set.id}\"", "file_results", "=", "ActiveFedora", "::", "SolrService", ".", "instance", ".", "conn", ".", "get", "(", "ActiveFedora", "::", "SolrService", ".", "select_path", ",", "params", ":", "{", "fq", ":", "[", "query", ",", "\"has_model_ssim:FileSet\"", "]", ",", "rows", ":", "0", "}", ")", "file_counts", "[", "admin_set", ".", "id", "]", "=", "file_results", "[", "'response'", "]", "[", "'numFound'", "]", "end", "file_counts", "end" ]
Count number of files from admin set works @param [Array] AdminSets to count files in @return [Hash] admin set id keys and file count values
[ "Count", "number", "of", "files", "from", "admin", "set", "works" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/admin_set_service.rb#L56-L68
train
samvera/hyrax
lib/hyrax/configuration.rb
Hyrax.Configuration.register_curation_concern
def register_curation_concern(*curation_concern_types) Array.wrap(curation_concern_types).flatten.compact.each do |cc_type| @registered_concerns << cc_type unless @registered_concerns.include?(cc_type) end end
ruby
def register_curation_concern(*curation_concern_types) Array.wrap(curation_concern_types).flatten.compact.each do |cc_type| @registered_concerns << cc_type unless @registered_concerns.include?(cc_type) end end
[ "def", "register_curation_concern", "(", "*", "curation_concern_types", ")", "Array", ".", "wrap", "(", "curation_concern_types", ")", ".", "flatten", ".", "compact", ".", "each", "do", "|", "cc_type", "|", "@registered_concerns", "<<", "cc_type", "unless", "@registered_concerns", ".", "include?", "(", "cc_type", ")", "end", "end" ]
Registers the given curation concern model in the configuration @param [Array<Symbol>,Symbol] curation_concern_types
[ "Registers", "the", "given", "curation", "concern", "model", "in", "the", "configuration" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/lib/hyrax/configuration.rb#L207-L211
train
samvera/hyrax
app/presenters/hyrax/admin_set_options_presenter.rb
Hyrax.AdminSetOptionsPresenter.select_options
def select_options(access = :deposit) @service.search_results(access).map do |admin_set| [admin_set.to_s, admin_set.id, data_attributes(admin_set)] end end
ruby
def select_options(access = :deposit) @service.search_results(access).map do |admin_set| [admin_set.to_s, admin_set.id, data_attributes(admin_set)] end end
[ "def", "select_options", "(", "access", "=", ":deposit", ")", "@service", ".", "search_results", "(", "access", ")", ".", "map", "do", "|", "admin_set", "|", "[", "admin_set", ".", "to_s", ",", "admin_set", ".", "id", ",", "data_attributes", "(", "admin_set", ")", "]", "end", "end" ]
Return AdminSet selectbox options based on access type @param [Symbol] access :deposit, :read, or :edit
[ "Return", "AdminSet", "selectbox", "options", "based", "on", "access", "type" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/admin_set_options_presenter.rb#L10-L14
train
samvera/hyrax
app/presenters/hyrax/admin_set_options_presenter.rb
Hyrax.AdminSetOptionsPresenter.data_attributes
def data_attributes(admin_set) # Get permission template associated with this AdminSet (if any) permission_template = PermissionTemplate.find_by(source_id: admin_set.id) # Only add data attributes if permission template exists return {} unless permission_template attributes_for(permission_template: permission_template) end
ruby
def data_attributes(admin_set) # Get permission template associated with this AdminSet (if any) permission_template = PermissionTemplate.find_by(source_id: admin_set.id) # Only add data attributes if permission template exists return {} unless permission_template attributes_for(permission_template: permission_template) end
[ "def", "data_attributes", "(", "admin_set", ")", "permission_template", "=", "PermissionTemplate", ".", "find_by", "(", "source_id", ":", "admin_set", ".", "id", ")", "return", "{", "}", "unless", "permission_template", "attributes_for", "(", "permission_template", ":", "permission_template", ")", "end" ]
Create a hash of HTML5 'data' attributes. These attributes are added to select_options and later utilized by Javascript to limit new Work options based on AdminSet selected
[ "Create", "a", "hash", "of", "HTML5", "data", "attributes", ".", "These", "attributes", "are", "added", "to", "select_options", "and", "later", "utilized", "by", "Javascript", "to", "limit", "new", "Work", "options", "based", "on", "AdminSet", "selected" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/admin_set_options_presenter.rb#L20-L27
train
samvera/hyrax
app/presenters/hyrax/admin_set_options_presenter.rb
Hyrax.AdminSetOptionsPresenter.sharing?
def sharing?(permission_template:) wf = workflow(permission_template: permission_template) return false unless wf wf.allows_access_grant? end
ruby
def sharing?(permission_template:) wf = workflow(permission_template: permission_template) return false unless wf wf.allows_access_grant? end
[ "def", "sharing?", "(", "permission_template", ":", ")", "wf", "=", "workflow", "(", "permission_template", ":", "permission_template", ")", "return", "false", "unless", "wf", "wf", ".", "allows_access_grant?", "end" ]
Does the workflow for the currently selected permission template allow sharing?
[ "Does", "the", "workflow", "for", "the", "currently", "selected", "permission", "template", "allow", "sharing?" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/admin_set_options_presenter.rb#L45-L49
train
samvera/hyrax
app/controllers/concerns/hyrax/local_file_downloads_controller_behavior.rb
Hyrax.LocalFileDownloadsControllerBehavior.send_local_content
def send_local_content response.headers['Accept-Ranges'] = 'bytes' if request.head? local_content_head elsif request.headers['Range'] send_range_for_local_file else send_local_file_contents end end
ruby
def send_local_content response.headers['Accept-Ranges'] = 'bytes' if request.head? local_content_head elsif request.headers['Range'] send_range_for_local_file else send_local_file_contents end end
[ "def", "send_local_content", "response", ".", "headers", "[", "'Accept-Ranges'", "]", "=", "'bytes'", "if", "request", ".", "head?", "local_content_head", "elsif", "request", ".", "headers", "[", "'Range'", "]", "send_range_for_local_file", "else", "send_local_file_contents", "end", "end" ]
Handle the HTTP show request
[ "Handle", "the", "HTTP", "show", "request" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/concerns/hyrax/local_file_downloads_controller_behavior.rb#L6-L15
train
samvera/hyrax
app/controllers/concerns/hyrax/local_file_downloads_controller_behavior.rb
Hyrax.LocalFileDownloadsControllerBehavior.send_range_for_local_file
def send_range_for_local_file _, range = request.headers['Range'].split('bytes=') from, to = range.split('-').map(&:to_i) to = local_file_size - 1 unless to length = to - from + 1 response.headers['Content-Range'] = "bytes #{from}-#{to}/#{local_file_size}" response.headers['Content-Length'] = length.to_s self.status = 206 prepare_local_file_headers # For derivatives stored on the local file system send_data IO.binread(file, length, from), local_derivative_download_options.merge(status: status) end
ruby
def send_range_for_local_file _, range = request.headers['Range'].split('bytes=') from, to = range.split('-').map(&:to_i) to = local_file_size - 1 unless to length = to - from + 1 response.headers['Content-Range'] = "bytes #{from}-#{to}/#{local_file_size}" response.headers['Content-Length'] = length.to_s self.status = 206 prepare_local_file_headers # For derivatives stored on the local file system send_data IO.binread(file, length, from), local_derivative_download_options.merge(status: status) end
[ "def", "send_range_for_local_file", "_", ",", "range", "=", "request", ".", "headers", "[", "'Range'", "]", ".", "split", "(", "'bytes='", ")", "from", ",", "to", "=", "range", ".", "split", "(", "'-'", ")", ".", "map", "(", "&", ":to_i", ")", "to", "=", "local_file_size", "-", "1", "unless", "to", "length", "=", "to", "-", "from", "+", "1", "response", ".", "headers", "[", "'Content-Range'", "]", "=", "\"bytes #{from}-#{to}/#{local_file_size}\"", "response", ".", "headers", "[", "'Content-Length'", "]", "=", "length", ".", "to_s", "self", ".", "status", "=", "206", "prepare_local_file_headers", "send_data", "IO", ".", "binread", "(", "file", ",", "length", ",", "from", ")", ",", "local_derivative_download_options", ".", "merge", "(", "status", ":", "status", ")", "end" ]
render an HTTP Range response
[ "render", "an", "HTTP", "Range", "response" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/concerns/hyrax/local_file_downloads_controller_behavior.rb#L18-L29
train
samvera/hyrax
app/services/hyrax/admin_set_create_service.rb
Hyrax.AdminSetCreateService.create
def create admin_set.creator = [creating_user.user_key] if creating_user admin_set.save.tap do |result| if result ActiveRecord::Base.transaction do permission_template = create_permission_template workflow = create_workflows_for(permission_template: permission_template) create_default_access_for(permission_template: permission_template, workflow: workflow) if admin_set.default_set? end end end end
ruby
def create admin_set.creator = [creating_user.user_key] if creating_user admin_set.save.tap do |result| if result ActiveRecord::Base.transaction do permission_template = create_permission_template workflow = create_workflows_for(permission_template: permission_template) create_default_access_for(permission_template: permission_template, workflow: workflow) if admin_set.default_set? end end end end
[ "def", "create", "admin_set", ".", "creator", "=", "[", "creating_user", ".", "user_key", "]", "if", "creating_user", "admin_set", ".", "save", ".", "tap", "do", "|", "result", "|", "if", "result", "ActiveRecord", "::", "Base", ".", "transaction", "do", "permission_template", "=", "create_permission_template", "workflow", "=", "create_workflows_for", "(", "permission_template", ":", "permission_template", ")", "create_default_access_for", "(", "permission_template", ":", "permission_template", ",", "workflow", ":", "workflow", ")", "if", "admin_set", ".", "default_set?", "end", "end", "end", "end" ]
Creates an admin set, setting the creator and the default access controls. @return [TrueClass, FalseClass] true if it was successful
[ "Creates", "an", "admin", "set", "setting", "the", "creator", "and", "the", "default", "access", "controls", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/admin_set_create_service.rb#L55-L66
train
samvera/hyrax
app/services/hyrax/admin_set_create_service.rb
Hyrax.AdminSetCreateService.create_default_access_for
def create_default_access_for(permission_template:, workflow:) permission_template.access_grants.create(agent_type: 'group', agent_id: ::Ability.registered_group_name, access: Hyrax::PermissionTemplateAccess::DEPOSIT) deposit = Sipity::Role[Hyrax::RoleRegistry::DEPOSITING] workflow.update_responsibilities(role: deposit, agents: Hyrax::Group.new('registered')) end
ruby
def create_default_access_for(permission_template:, workflow:) permission_template.access_grants.create(agent_type: 'group', agent_id: ::Ability.registered_group_name, access: Hyrax::PermissionTemplateAccess::DEPOSIT) deposit = Sipity::Role[Hyrax::RoleRegistry::DEPOSITING] workflow.update_responsibilities(role: deposit, agents: Hyrax::Group.new('registered')) end
[ "def", "create_default_access_for", "(", "permission_template", ":", ",", "workflow", ":", ")", "permission_template", ".", "access_grants", ".", "create", "(", "agent_type", ":", "'group'", ",", "agent_id", ":", "::", "Ability", ".", "registered_group_name", ",", "access", ":", "Hyrax", "::", "PermissionTemplateAccess", "::", "DEPOSIT", ")", "deposit", "=", "Sipity", "::", "Role", "[", "Hyrax", "::", "RoleRegistry", "::", "DEPOSITING", "]", "workflow", ".", "update_responsibilities", "(", "role", ":", "deposit", ",", "agents", ":", "Hyrax", "::", "Group", ".", "new", "(", "'registered'", ")", ")", "end" ]
Gives deposit access to registered users to default AdminSet
[ "Gives", "deposit", "access", "to", "registered", "users", "to", "default", "AdminSet" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/admin_set_create_service.rb#L122-L126
train
samvera/hyrax
app/services/hyrax/microdata.rb
Hyrax.Microdata.flatten
def flatten(hash) hash.each_with_object({}) do |(key, value), h| if value.instance_of?(Hash) value.map do |k, v| # We could add recursion here if we ever had more than 2 levels h["#{key}.#{k}"] = v end else h[key] = value end end end
ruby
def flatten(hash) hash.each_with_object({}) do |(key, value), h| if value.instance_of?(Hash) value.map do |k, v| # We could add recursion here if we ever had more than 2 levels h["#{key}.#{k}"] = v end else h[key] = value end end end
[ "def", "flatten", "(", "hash", ")", "hash", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "h", "|", "if", "value", ".", "instance_of?", "(", "Hash", ")", "value", ".", "map", "do", "|", "k", ",", "v", "|", "h", "[", "\"#{key}.#{k}\"", "]", "=", "v", "end", "else", "h", "[", "key", "]", "=", "value", "end", "end", "end" ]
Given a deeply nested hash, return a single hash
[ "Given", "a", "deeply", "nested", "hash", "return", "a", "single", "hash" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/microdata.rb#L84-L95
train
samvera/hyrax
app/presenters/hyrax/member_presenter_factory.rb
Hyrax.MemberPresenterFactory.file_set_ids
def file_set_ids @file_set_ids ||= begin ActiveFedora::SolrService.query("{!field f=has_model_ssim}FileSet", rows: 10_000, fl: ActiveFedora.id_field, fq: "{!join from=ordered_targets_ssim to=id}id:\"#{id}/list_source\"") .flat_map { |x| x.fetch(ActiveFedora.id_field, []) } end end
ruby
def file_set_ids @file_set_ids ||= begin ActiveFedora::SolrService.query("{!field f=has_model_ssim}FileSet", rows: 10_000, fl: ActiveFedora.id_field, fq: "{!join from=ordered_targets_ssim to=id}id:\"#{id}/list_source\"") .flat_map { |x| x.fetch(ActiveFedora.id_field, []) } end end
[ "def", "file_set_ids", "@file_set_ids", "||=", "begin", "ActiveFedora", "::", "SolrService", ".", "query", "(", "\"{!field f=has_model_ssim}FileSet\"", ",", "rows", ":", "10_000", ",", "fl", ":", "ActiveFedora", ".", "id_field", ",", "fq", ":", "\"{!join from=ordered_targets_ssim to=id}id:\\\"#{id}/list_source\\\"\"", ")", ".", "flat_map", "{", "|", "x", "|", "x", ".", "fetch", "(", "ActiveFedora", ".", "id_field", ",", "[", "]", ")", "}", "end", "end" ]
These are the file sets that belong to this work, but not necessarily in order. Arbitrarily maxed at 10 thousand; had to specify rows due to solr's default of 10
[ "These", "are", "the", "file", "sets", "that", "belong", "to", "this", "work", "but", "not", "necessarily", "in", "order", ".", "Arbitrarily", "maxed", "at", "10", "thousand", ";", "had", "to", "specify", "rows", "due", "to", "solr", "s", "default", "of", "10" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/member_presenter_factory.rb#L54-L62
train
samvera/hyrax
lib/hyrax/rails/routes.rb
ActionDispatch::Routing.Mapper.namespaced_resources
def namespaced_resources(target, opts = {}, &block) if target.include?('/') the_namespace = target[0..target.index('/') - 1] new_target = target[target.index('/') + 1..-1] namespace the_namespace, ROUTE_OPTIONS.fetch(the_namespace, {}) do namespaced_resources(new_target, opts, &block) end else resources target, opts do yield if block_given? end end end
ruby
def namespaced_resources(target, opts = {}, &block) if target.include?('/') the_namespace = target[0..target.index('/') - 1] new_target = target[target.index('/') + 1..-1] namespace the_namespace, ROUTE_OPTIONS.fetch(the_namespace, {}) do namespaced_resources(new_target, opts, &block) end else resources target, opts do yield if block_given? end end end
[ "def", "namespaced_resources", "(", "target", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "if", "target", ".", "include?", "(", "'/'", ")", "the_namespace", "=", "target", "[", "0", "..", "target", ".", "index", "(", "'/'", ")", "-", "1", "]", "new_target", "=", "target", "[", "target", ".", "index", "(", "'/'", ")", "+", "1", "..", "-", "1", "]", "namespace", "the_namespace", ",", "ROUTE_OPTIONS", ".", "fetch", "(", "the_namespace", ",", "{", "}", ")", "do", "namespaced_resources", "(", "new_target", ",", "opts", ",", "&", "block", ")", "end", "else", "resources", "target", ",", "opts", "do", "yield", "if", "block_given?", "end", "end", "end" ]
Namespaces routes appropriately @example namespaced_resources("hyrax/my_work") is equivalent to namespace "hyrax", path: :concern do resources "my_work", except: [:index] end
[ "Namespaces", "routes", "appropriately" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/lib/hyrax/rails/routes.rb#L59-L71
train
samvera/hyrax
app/presenters/hyrax/work_show_presenter.rb
Hyrax.WorkShowPresenter.manifest_metadata
def manifest_metadata metadata = [] Hyrax.config.iiif_metadata_fields.each do |field| metadata << { 'label' => I18n.t("simple_form.labels.defaults.#{field}"), 'value' => Array.wrap(send(field).map { |f| Loofah.fragment(f.to_s).scrub!(:whitewash).to_s }) } end metadata end
ruby
def manifest_metadata metadata = [] Hyrax.config.iiif_metadata_fields.each do |field| metadata << { 'label' => I18n.t("simple_form.labels.defaults.#{field}"), 'value' => Array.wrap(send(field).map { |f| Loofah.fragment(f.to_s).scrub!(:whitewash).to_s }) } end metadata end
[ "def", "manifest_metadata", "metadata", "=", "[", "]", "Hyrax", ".", "config", ".", "iiif_metadata_fields", ".", "each", "do", "|", "field", "|", "metadata", "<<", "{", "'label'", "=>", "I18n", ".", "t", "(", "\"simple_form.labels.defaults.#{field}\"", ")", ",", "'value'", "=>", "Array", ".", "wrap", "(", "send", "(", "field", ")", ".", "map", "{", "|", "f", "|", "Loofah", ".", "fragment", "(", "f", ".", "to_s", ")", ".", "scrub!", "(", ":whitewash", ")", ".", "to_s", "}", ")", "}", "end", "metadata", "end" ]
IIIF metadata for inclusion in the manifest Called by the `iiif_manifest` gem to add metadata @return [Array] array of metadata hashes
[ "IIIF", "metadata", "for", "inclusion", "in", "the", "manifest", "Called", "by", "the", "iiif_manifest", "gem", "to", "add", "metadata" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/work_show_presenter.rb#L216-L225
train
samvera/hyrax
app/presenters/hyrax/work_show_presenter.rb
Hyrax.WorkShowPresenter.authorized_item_ids
def authorized_item_ids @member_item_list_ids ||= begin items = ordered_ids items.delete_if { |m| !current_ability.can?(:read, m) } if Flipflop.hide_private_items? items end end
ruby
def authorized_item_ids @member_item_list_ids ||= begin items = ordered_ids items.delete_if { |m| !current_ability.can?(:read, m) } if Flipflop.hide_private_items? items end end
[ "def", "authorized_item_ids", "@member_item_list_ids", "||=", "begin", "items", "=", "ordered_ids", "items", ".", "delete_if", "{", "|", "m", "|", "!", "current_ability", ".", "can?", "(", ":read", ",", "m", ")", "}", "if", "Flipflop", ".", "hide_private_items?", "items", "end", "end" ]
list of item ids to display is based on ordered_ids
[ "list", "of", "item", "ids", "to", "display", "is", "based", "on", "ordered_ids" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/work_show_presenter.rb#L237-L243
train
samvera/hyrax
app/presenters/hyrax/work_show_presenter.rb
Hyrax.WorkShowPresenter.paginated_item_list
def paginated_item_list(page_array:) Kaminari.paginate_array(page_array, total_count: page_array.size).page(current_page).per(rows_from_params) end
ruby
def paginated_item_list(page_array:) Kaminari.paginate_array(page_array, total_count: page_array.size).page(current_page).per(rows_from_params) end
[ "def", "paginated_item_list", "(", "page_array", ":", ")", "Kaminari", ".", "paginate_array", "(", "page_array", ",", "total_count", ":", "page_array", ".", "size", ")", ".", "page", "(", "current_page", ")", ".", "per", "(", "rows_from_params", ")", "end" ]
Uses kaminari to paginate an array to avoid need for solr documents for items here
[ "Uses", "kaminari", "to", "paginate", "an", "array", "to", "avoid", "need", "for", "solr", "documents", "for", "items", "here" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/work_show_presenter.rb#L246-L248
train
samvera/hyrax
app/helpers/hyrax/collections_helper.rb
Hyrax.CollectionsHelper.single_item_action_form_fields
def single_item_action_form_fields(form, document, action) render 'hyrax/dashboard/collections/single_item_action_fields', form: form, document: document, action: action end
ruby
def single_item_action_form_fields(form, document, action) render 'hyrax/dashboard/collections/single_item_action_fields', form: form, document: document, action: action end
[ "def", "single_item_action_form_fields", "(", "form", ",", "document", ",", "action", ")", "render", "'hyrax/dashboard/collections/single_item_action_fields'", ",", "form", ":", "form", ",", "document", ":", "document", ",", "action", ":", "action", "end" ]
add hidden fields to a form for performing an action on a single document on a collection
[ "add", "hidden", "fields", "to", "a", "form", "for", "performing", "an", "action", "on", "a", "single", "document", "on", "a", "collection" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/helpers/hyrax/collections_helper.rb#L74-L76
train
samvera/hyrax
app/controllers/concerns/hyrax/works_controller_behavior.rb
Hyrax.WorksControllerBehavior.show
def show @user_collections = user_collections respond_to do |wants| wants.html { presenter && parent_presenter } wants.json do # load and authorize @curation_concern manually because it's skipped for html @curation_concern = _curation_concern_type.find(params[:id]) unless curation_concern authorize! :show, @curation_concern render :show, status: :ok end additional_response_formats(wants) wants.ttl do render body: presenter.export_as_ttl, content_type: 'text/turtle' end wants.jsonld do render body: presenter.export_as_jsonld, content_type: 'application/ld+json' end wants.nt do render body: presenter.export_as_nt, content_type: 'application/n-triples' end end end
ruby
def show @user_collections = user_collections respond_to do |wants| wants.html { presenter && parent_presenter } wants.json do # load and authorize @curation_concern manually because it's skipped for html @curation_concern = _curation_concern_type.find(params[:id]) unless curation_concern authorize! :show, @curation_concern render :show, status: :ok end additional_response_formats(wants) wants.ttl do render body: presenter.export_as_ttl, content_type: 'text/turtle' end wants.jsonld do render body: presenter.export_as_jsonld, content_type: 'application/ld+json' end wants.nt do render body: presenter.export_as_nt, content_type: 'application/n-triples' end end end
[ "def", "show", "@user_collections", "=", "user_collections", "respond_to", "do", "|", "wants", "|", "wants", ".", "html", "{", "presenter", "&&", "parent_presenter", "}", "wants", ".", "json", "do", "@curation_concern", "=", "_curation_concern_type", ".", "find", "(", "params", "[", ":id", "]", ")", "unless", "curation_concern", "authorize!", ":show", ",", "@curation_concern", "render", ":show", ",", "status", ":", ":ok", "end", "additional_response_formats", "(", "wants", ")", "wants", ".", "ttl", "do", "render", "body", ":", "presenter", ".", "export_as_ttl", ",", "content_type", ":", "'text/turtle'", "end", "wants", ".", "jsonld", "do", "render", "body", ":", "presenter", ".", "export_as_jsonld", ",", "content_type", ":", "'application/ld+json'", "end", "wants", ".", "nt", "do", "render", "body", ":", "presenter", ".", "export_as_nt", ",", "content_type", ":", "'application/n-triples'", "end", "end", "end" ]
Finds a solr document matching the id and sets @presenter @raise CanCan::AccessDenied if the document is not found or the user doesn't have access to it.
[ "Finds", "a", "solr", "document", "matching", "the", "id", "and", "sets" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/concerns/hyrax/works_controller_behavior.rb#L69-L91
train
samvera/hyrax
app/controllers/concerns/hyrax/works_controller_behavior.rb
Hyrax.WorksControllerBehavior.search_result_document
def search_result_document(search_params) _, document_list = search_results(search_params) return document_list.first unless document_list.empty? document_not_found! end
ruby
def search_result_document(search_params) _, document_list = search_results(search_params) return document_list.first unless document_list.empty? document_not_found! end
[ "def", "search_result_document", "(", "search_params", ")", "_", ",", "document_list", "=", "search_results", "(", "search_params", ")", "return", "document_list", ".", "first", "unless", "document_list", ".", "empty?", "document_not_found!", "end" ]
Only returns unsuppressed documents the user has read access to
[ "Only", "returns", "unsuppressed", "documents", "the", "user", "has", "read", "access", "to" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/concerns/hyrax/works_controller_behavior.rb#L207-L211
train
samvera/hyrax
app/controllers/concerns/hyrax/works_controller_behavior.rb
Hyrax.WorksControllerBehavior.attributes_for_actor
def attributes_for_actor raw_params = params[hash_key_for_curation_concern] attributes = if raw_params work_form_service.form_class(curation_concern).model_attributes(raw_params) else {} end # If they selected a BrowseEverything file, but then clicked the # remove button, it will still show up in `selected_files`, but # it will no longer be in uploaded_files. By checking the # intersection, we get the files they added via BrowseEverything # that they have not removed from the upload widget. uploaded_files = params.fetch(:uploaded_files, []) selected_files = params.fetch(:selected_files, {}).values browse_everything_urls = uploaded_files & selected_files.map { |f| f[:url] } # we need the hash of files with url and file_name browse_everything_files = selected_files .select { |v| uploaded_files.include?(v[:url]) } attributes[:remote_files] = browse_everything_files # Strip out any BrowseEverthing files from the regular uploads. attributes[:uploaded_files] = uploaded_files - browse_everything_urls attributes end
ruby
def attributes_for_actor raw_params = params[hash_key_for_curation_concern] attributes = if raw_params work_form_service.form_class(curation_concern).model_attributes(raw_params) else {} end # If they selected a BrowseEverything file, but then clicked the # remove button, it will still show up in `selected_files`, but # it will no longer be in uploaded_files. By checking the # intersection, we get the files they added via BrowseEverything # that they have not removed from the upload widget. uploaded_files = params.fetch(:uploaded_files, []) selected_files = params.fetch(:selected_files, {}).values browse_everything_urls = uploaded_files & selected_files.map { |f| f[:url] } # we need the hash of files with url and file_name browse_everything_files = selected_files .select { |v| uploaded_files.include?(v[:url]) } attributes[:remote_files] = browse_everything_files # Strip out any BrowseEverthing files from the regular uploads. attributes[:uploaded_files] = uploaded_files - browse_everything_urls attributes end
[ "def", "attributes_for_actor", "raw_params", "=", "params", "[", "hash_key_for_curation_concern", "]", "attributes", "=", "if", "raw_params", "work_form_service", ".", "form_class", "(", "curation_concern", ")", ".", "model_attributes", "(", "raw_params", ")", "else", "{", "}", "end", "uploaded_files", "=", "params", ".", "fetch", "(", ":uploaded_files", ",", "[", "]", ")", "selected_files", "=", "params", ".", "fetch", "(", ":selected_files", ",", "{", "}", ")", ".", "values", "browse_everything_urls", "=", "uploaded_files", "&", "selected_files", ".", "map", "{", "|", "f", "|", "f", "[", ":url", "]", "}", "browse_everything_files", "=", "selected_files", ".", "select", "{", "|", "v", "|", "uploaded_files", ".", "include?", "(", "v", "[", ":url", "]", ")", "}", "attributes", "[", ":remote_files", "]", "=", "browse_everything_files", "attributes", "[", ":uploaded_files", "]", "=", "uploaded_files", "-", "browse_everything_urls", "attributes", "end" ]
Add uploaded_files to the parameters received by the actor.
[ "Add", "uploaded_files", "to", "the", "parameters", "received", "by", "the", "actor", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/concerns/hyrax/works_controller_behavior.rb#L258-L284
train
samvera/hyrax
app/builders/hyrax/manifest_helper.rb
Hyrax.ManifestHelper.build_rendering
def build_rendering(file_set_id) file_set_document = query_for_rendering(file_set_id) label = file_set_document.label.present? ? ": #{file_set_document.label}" : '' mime = file_set_document.mime_type.present? ? file_set_document.mime_type : I18n.t("hyrax.manifest.unknown_mime_text") { '@id' => Hyrax::Engine.routes.url_helpers.download_url(file_set_document.id, host: @hostname), 'format' => mime, 'label' => I18n.t("hyrax.manifest.download_text") + label } end
ruby
def build_rendering(file_set_id) file_set_document = query_for_rendering(file_set_id) label = file_set_document.label.present? ? ": #{file_set_document.label}" : '' mime = file_set_document.mime_type.present? ? file_set_document.mime_type : I18n.t("hyrax.manifest.unknown_mime_text") { '@id' => Hyrax::Engine.routes.url_helpers.download_url(file_set_document.id, host: @hostname), 'format' => mime, 'label' => I18n.t("hyrax.manifest.download_text") + label } end
[ "def", "build_rendering", "(", "file_set_id", ")", "file_set_document", "=", "query_for_rendering", "(", "file_set_id", ")", "label", "=", "file_set_document", ".", "label", ".", "present?", "?", "\": #{file_set_document.label}\"", ":", "''", "mime", "=", "file_set_document", ".", "mime_type", ".", "present?", "?", "file_set_document", ".", "mime_type", ":", "I18n", ".", "t", "(", "\"hyrax.manifest.unknown_mime_text\"", ")", "{", "'@id'", "=>", "Hyrax", "::", "Engine", ".", "routes", ".", "url_helpers", ".", "download_url", "(", "file_set_document", ".", "id", ",", "host", ":", "@hostname", ")", ",", "'format'", "=>", "mime", ",", "'label'", "=>", "I18n", ".", "t", "(", "\"hyrax.manifest.download_text\"", ")", "+", "label", "}", "end" ]
Build a rendering hash @return [Hash] rendering
[ "Build", "a", "rendering", "hash" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/builders/hyrax/manifest_helper.rb#L18-L27
train
samvera/hyrax
spec/support/selectors.rb
Selectors.Dashboard.select_user
def select_user(user, role = 'Depositor') first('a.select2-choice').click find('.select2-input').set(user.user_key) sleep 1 first('div.select2-result-label').click within('div.add-users') do select(role) find('input.edit-collection-add-sharing-button').click end end
ruby
def select_user(user, role = 'Depositor') first('a.select2-choice').click find('.select2-input').set(user.user_key) sleep 1 first('div.select2-result-label').click within('div.add-users') do select(role) find('input.edit-collection-add-sharing-button').click end end
[ "def", "select_user", "(", "user", ",", "role", "=", "'Depositor'", ")", "first", "(", "'a.select2-choice'", ")", ".", "click", "find", "(", "'.select2-input'", ")", ".", "set", "(", "user", ".", "user_key", ")", "sleep", "1", "first", "(", "'div.select2-result-label'", ")", ".", "click", "within", "(", "'div.add-users'", ")", "do", "select", "(", "role", ")", "find", "(", "'input.edit-collection-add-sharing-button'", ")", ".", "click", "end", "end" ]
For use with javascript user selector that allows for searching for an existing user and granting them permission to an object. @param [User] user to select @param [String] role granting the user permission (e.g. 'Manager' | 'Depositor' | 'Viewer')
[ "For", "use", "with", "javascript", "user", "selector", "that", "allows", "for", "searching", "for", "an", "existing", "user", "and", "granting", "them", "permission", "to", "an", "object", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/spec/support/selectors.rb#L13-L22
train
samvera/hyrax
spec/support/selectors.rb
Selectors.Dashboard.select_collection
def select_collection(collection) first('a.select2-choice').click find('.select2-input').set(collection.title.first) expect(page).to have_css('div.select2-result-label') first('div.select2-result-label').click first('[data-behavior~=add-relationship]').click within('[data-behavior~=collection-relationships]') do within('table.table.table-striped') do expect(page).to have_content(collection.title.first) end end end
ruby
def select_collection(collection) first('a.select2-choice').click find('.select2-input').set(collection.title.first) expect(page).to have_css('div.select2-result-label') first('div.select2-result-label').click first('[data-behavior~=add-relationship]').click within('[data-behavior~=collection-relationships]') do within('table.table.table-striped') do expect(page).to have_content(collection.title.first) end end end
[ "def", "select_collection", "(", "collection", ")", "first", "(", "'a.select2-choice'", ")", ".", "click", "find", "(", "'.select2-input'", ")", ".", "set", "(", "collection", ".", "title", ".", "first", ")", "expect", "(", "page", ")", ".", "to", "have_css", "(", "'div.select2-result-label'", ")", "first", "(", "'div.select2-result-label'", ")", ".", "click", "first", "(", "'[data-behavior~=add-relationship]'", ")", ".", "click", "within", "(", "'[data-behavior~=collection-relationships]'", ")", "do", "within", "(", "'table.table.table-striped'", ")", "do", "expect", "(", "page", ")", ".", "to", "have_content", "(", "collection", ".", "title", ".", "first", ")", "end", "end", "end" ]
For use with javascript collection selector that allows for searching for an existing collection from works relationship tab. Adds the collection and validates that the collection is listed in the Collection Relationship table once added. @param [Collection] collection to select
[ "For", "use", "with", "javascript", "collection", "selector", "that", "allows", "for", "searching", "for", "an", "existing", "collection", "from", "works", "relationship", "tab", ".", "Adds", "the", "collection", "and", "validates", "that", "the", "collection", "is", "listed", "in", "the", "Collection", "Relationship", "table", "once", "added", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/spec/support/selectors.rb#L27-L38
train
samvera/hyrax
spec/support/selectors.rb
Selectors.Dashboard.select_member_of_collection
def select_member_of_collection(collection) find('#s2id_member_of_collection_ids').click find('.select2-input').set(collection.title.first) # Crude way of waiting for the AJAX response select2_results = [] time_elapsed = 0 while select2_results.empty? && time_elapsed < 30 begin_time = Time.now.to_f doc = Nokogiri::XML.parse(page.body) select2_results = doc.xpath('//html:li[contains(@class,"select2-result")]', html: 'http://www.w3.org/1999/xhtml') end_time = Time.now.to_f time_elapsed += end_time - begin_time end expect(page).to have_css('.select2-result') within ".select2-result" do find("span", text: collection.title.first).click end end
ruby
def select_member_of_collection(collection) find('#s2id_member_of_collection_ids').click find('.select2-input').set(collection.title.first) # Crude way of waiting for the AJAX response select2_results = [] time_elapsed = 0 while select2_results.empty? && time_elapsed < 30 begin_time = Time.now.to_f doc = Nokogiri::XML.parse(page.body) select2_results = doc.xpath('//html:li[contains(@class,"select2-result")]', html: 'http://www.w3.org/1999/xhtml') end_time = Time.now.to_f time_elapsed += end_time - begin_time end expect(page).to have_css('.select2-result') within ".select2-result" do find("span", text: collection.title.first).click end end
[ "def", "select_member_of_collection", "(", "collection", ")", "find", "(", "'#s2id_member_of_collection_ids'", ")", ".", "click", "find", "(", "'.select2-input'", ")", ".", "set", "(", "collection", ".", "title", ".", "first", ")", "select2_results", "=", "[", "]", "time_elapsed", "=", "0", "while", "select2_results", ".", "empty?", "&&", "time_elapsed", "<", "30", "begin_time", "=", "Time", ".", "now", ".", "to_f", "doc", "=", "Nokogiri", "::", "XML", ".", "parse", "(", "page", ".", "body", ")", "select2_results", "=", "doc", ".", "xpath", "(", "'//html:li[contains(@class,\"select2-result\")]'", ",", "html", ":", "'http://www.w3.org/1999/xhtml'", ")", "end_time", "=", "Time", ".", "now", ".", "to_f", "time_elapsed", "+=", "end_time", "-", "begin_time", "end", "expect", "(", "page", ")", ".", "to", "have_css", "(", "'.select2-result'", ")", "within", "\".select2-result\"", "do", "find", "(", "\"span\"", ",", "text", ":", "collection", ".", "title", ".", "first", ")", ".", "click", "end", "end" ]
For use with javascript collection selector that allows for searching for an existing collection from add to collection modal. Does not save the selection. The calling test is expected to click Save and validate the collection membership was added to the work. @param [Collection] collection to select
[ "For", "use", "with", "javascript", "collection", "selector", "that", "allows", "for", "searching", "for", "an", "existing", "collection", "from", "add", "to", "collection", "modal", ".", "Does", "not", "save", "the", "selection", ".", "The", "calling", "test", "is", "expected", "to", "click", "Save", "and", "validate", "the", "collection", "membership", "was", "added", "to", "the", "work", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/spec/support/selectors.rb#L43-L60
train
samvera/hyrax
app/presenters/hyrax/displays_image.rb
Hyrax.DisplaysImage.display_image
def display_image return nil unless ::FileSet.exists?(id) && solr_document.image? && current_ability.can?(:read, id) # @todo this is slow, find a better way (perhaps index iiif url): original_file = ::FileSet.find(id).original_file url = Hyrax.config.iiif_image_url_builder.call( original_file.id, request.base_url, Hyrax.config.iiif_image_size_default ) # @see https://github.com/samvera-labs/iiif_manifest IIIFManifest::DisplayImage.new(url, width: 640, height: 480, iiif_endpoint: iiif_endpoint(original_file.id)) end
ruby
def display_image return nil unless ::FileSet.exists?(id) && solr_document.image? && current_ability.can?(:read, id) # @todo this is slow, find a better way (perhaps index iiif url): original_file = ::FileSet.find(id).original_file url = Hyrax.config.iiif_image_url_builder.call( original_file.id, request.base_url, Hyrax.config.iiif_image_size_default ) # @see https://github.com/samvera-labs/iiif_manifest IIIFManifest::DisplayImage.new(url, width: 640, height: 480, iiif_endpoint: iiif_endpoint(original_file.id)) end
[ "def", "display_image", "return", "nil", "unless", "::", "FileSet", ".", "exists?", "(", "id", ")", "&&", "solr_document", ".", "image?", "&&", "current_ability", ".", "can?", "(", ":read", ",", "id", ")", "original_file", "=", "::", "FileSet", ".", "find", "(", "id", ")", ".", "original_file", "url", "=", "Hyrax", ".", "config", ".", "iiif_image_url_builder", ".", "call", "(", "original_file", ".", "id", ",", "request", ".", "base_url", ",", "Hyrax", ".", "config", ".", "iiif_image_size_default", ")", "IIIFManifest", "::", "DisplayImage", ".", "new", "(", "url", ",", "width", ":", "640", ",", "height", ":", "480", ",", "iiif_endpoint", ":", "iiif_endpoint", "(", "original_file", ".", "id", ")", ")", "end" ]
Creates a display image only where FileSet is an image. @return [IIIFManifest::DisplayImage] the display image required by the manifest builder.
[ "Creates", "a", "display", "image", "only", "where", "FileSet", "is", "an", "image", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/displays_image.rb#L12-L27
train
samvera/hyrax
app/services/hyrax/file_set_fixity_check_service.rb
Hyrax.FileSetFixityCheckService.fixity_check_file_version
def fixity_check_file_version(file_id, version_uri) latest_fixity_check = ChecksumAuditLog.logs_for(file_set.id, checked_uri: version_uri).first return latest_fixity_check unless needs_fixity_check?(latest_fixity_check) if async_jobs FixityCheckJob.perform_later(version_uri.to_s, file_set_id: file_set.id, file_id: file_id) else FixityCheckJob.perform_now(version_uri.to_s, file_set_id: file_set.id, file_id: file_id) end end
ruby
def fixity_check_file_version(file_id, version_uri) latest_fixity_check = ChecksumAuditLog.logs_for(file_set.id, checked_uri: version_uri).first return latest_fixity_check unless needs_fixity_check?(latest_fixity_check) if async_jobs FixityCheckJob.perform_later(version_uri.to_s, file_set_id: file_set.id, file_id: file_id) else FixityCheckJob.perform_now(version_uri.to_s, file_set_id: file_set.id, file_id: file_id) end end
[ "def", "fixity_check_file_version", "(", "file_id", ",", "version_uri", ")", "latest_fixity_check", "=", "ChecksumAuditLog", ".", "logs_for", "(", "file_set", ".", "id", ",", "checked_uri", ":", "version_uri", ")", ".", "first", "return", "latest_fixity_check", "unless", "needs_fixity_check?", "(", "latest_fixity_check", ")", "if", "async_jobs", "FixityCheckJob", ".", "perform_later", "(", "version_uri", ".", "to_s", ",", "file_set_id", ":", "file_set", ".", "id", ",", "file_id", ":", "file_id", ")", "else", "FixityCheckJob", ".", "perform_now", "(", "version_uri", ".", "to_s", ",", "file_set_id", ":", "file_set", ".", "id", ",", "file_id", ":", "file_id", ")", "end", "end" ]
Retrieve or generate the fixity check for a specific version of a file @param [String] file_id used to find the file within its parent object (usually "original_file") @param [String] version_uri the version to be fixity checked (or the file uri for non-versioned files)
[ "Retrieve", "or", "generate", "the", "fixity", "check", "for", "a", "specific", "version", "of", "a", "file" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/file_set_fixity_check_service.rb#L82-L91
train
samvera/hyrax
app/services/hyrax/file_set_fixity_check_service.rb
Hyrax.FileSetFixityCheckService.needs_fixity_check?
def needs_fixity_check?(latest_fixity_check) return true unless latest_fixity_check unless latest_fixity_check.updated_at logger.warn "***FIXITY*** problem with fixity check log! Latest Fixity check is not nil, but updated_at is not set #{latest_fixity_check}" return true end days_since_last_fixity_check(latest_fixity_check) >= max_days_between_fixity_checks end
ruby
def needs_fixity_check?(latest_fixity_check) return true unless latest_fixity_check unless latest_fixity_check.updated_at logger.warn "***FIXITY*** problem with fixity check log! Latest Fixity check is not nil, but updated_at is not set #{latest_fixity_check}" return true end days_since_last_fixity_check(latest_fixity_check) >= max_days_between_fixity_checks end
[ "def", "needs_fixity_check?", "(", "latest_fixity_check", ")", "return", "true", "unless", "latest_fixity_check", "unless", "latest_fixity_check", ".", "updated_at", "logger", ".", "warn", "\"***FIXITY*** problem with fixity check log! Latest Fixity check is not nil, but updated_at is not set #{latest_fixity_check}\"", "return", "true", "end", "days_since_last_fixity_check", "(", "latest_fixity_check", ")", ">=", "max_days_between_fixity_checks", "end" ]
Check if time since the last fixity check is greater than the maximum days allowed between fixity checks @param [ChecksumAuditLog] latest_fixity_check the most recent fixity check
[ "Check", "if", "time", "since", "the", "last", "fixity", "check", "is", "greater", "than", "the", "maximum", "days", "allowed", "between", "fixity", "checks" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/services/hyrax/file_set_fixity_check_service.rb#L95-L102
train
samvera/hyrax
app/controllers/concerns/hyrax/embargoes_controller_behavior.rb
Hyrax.EmbargoesControllerBehavior.destroy
def destroy Hyrax::Actors::EmbargoActor.new(curation_concern).destroy flash[:notice] = curation_concern.embargo_history.last if curation_concern.work? && curation_concern.file_sets.present? redirect_to confirm_permission_path else redirect_to edit_embargo_path end end
ruby
def destroy Hyrax::Actors::EmbargoActor.new(curation_concern).destroy flash[:notice] = curation_concern.embargo_history.last if curation_concern.work? && curation_concern.file_sets.present? redirect_to confirm_permission_path else redirect_to edit_embargo_path end end
[ "def", "destroy", "Hyrax", "::", "Actors", "::", "EmbargoActor", ".", "new", "(", "curation_concern", ")", ".", "destroy", "flash", "[", ":notice", "]", "=", "curation_concern", ".", "embargo_history", ".", "last", "if", "curation_concern", ".", "work?", "&&", "curation_concern", ".", "file_sets", ".", "present?", "redirect_to", "confirm_permission_path", "else", "redirect_to", "edit_embargo_path", "end", "end" ]
Removes a single embargo
[ "Removes", "a", "single", "embargo" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/concerns/hyrax/embargoes_controller_behavior.rb#L15-L23
train
samvera/hyrax
app/controllers/concerns/hyrax/embargoes_controller_behavior.rb
Hyrax.EmbargoesControllerBehavior.update
def update filter_docs_with_edit_access! copy_visibility = params[:embargoes].values.map { |h| h[:copy_visibility] } ActiveFedora::Base.find(batch).each do |curation_concern| Hyrax::Actors::EmbargoActor.new(curation_concern).destroy # if the concern is a FileSet, set its visibility and skip the copy_visibility_to_files, which is built for Works if curation_concern.file_set? curation_concern.visibility = curation_concern.to_solr["visibility_after_embargo_ssim"] curation_concern.save! elsif copy_visibility.include?(curation_concern.id) curation_concern.copy_visibility_to_files end end redirect_to embargoes_path, notice: t('.embargo_deactivated') end
ruby
def update filter_docs_with_edit_access! copy_visibility = params[:embargoes].values.map { |h| h[:copy_visibility] } ActiveFedora::Base.find(batch).each do |curation_concern| Hyrax::Actors::EmbargoActor.new(curation_concern).destroy # if the concern is a FileSet, set its visibility and skip the copy_visibility_to_files, which is built for Works if curation_concern.file_set? curation_concern.visibility = curation_concern.to_solr["visibility_after_embargo_ssim"] curation_concern.save! elsif copy_visibility.include?(curation_concern.id) curation_concern.copy_visibility_to_files end end redirect_to embargoes_path, notice: t('.embargo_deactivated') end
[ "def", "update", "filter_docs_with_edit_access!", "copy_visibility", "=", "params", "[", ":embargoes", "]", ".", "values", ".", "map", "{", "|", "h", "|", "h", "[", ":copy_visibility", "]", "}", "ActiveFedora", "::", "Base", ".", "find", "(", "batch", ")", ".", "each", "do", "|", "curation_concern", "|", "Hyrax", "::", "Actors", "::", "EmbargoActor", ".", "new", "(", "curation_concern", ")", ".", "destroy", "if", "curation_concern", ".", "file_set?", "curation_concern", ".", "visibility", "=", "curation_concern", ".", "to_solr", "[", "\"visibility_after_embargo_ssim\"", "]", "curation_concern", ".", "save!", "elsif", "copy_visibility", ".", "include?", "(", "curation_concern", ".", "id", ")", "curation_concern", ".", "copy_visibility_to_files", "end", "end", "redirect_to", "embargoes_path", ",", "notice", ":", "t", "(", "'.embargo_deactivated'", ")", "end" ]
Updates a batch of embargos
[ "Updates", "a", "batch", "of", "embargos" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/concerns/hyrax/embargoes_controller_behavior.rb#L26-L40
train
samvera/hyrax
app/indexers/hyrax/indexes_workflow.rb
Hyrax.IndexesWorkflow.index_workflow_fields
def index_workflow_fields(solr_document) return unless object.persisted? entity = PowerConverter.convert_to_sipity_entity(object) return if entity.nil? solr_document[workflow_role_field] = workflow_roles(entity).map { |role| "#{entity.workflow.permission_template.source_id}-#{entity.workflow.name}-#{role}" } solr_document[workflow_state_name_field] = entity.workflow_state.name if entity.workflow_state end
ruby
def index_workflow_fields(solr_document) return unless object.persisted? entity = PowerConverter.convert_to_sipity_entity(object) return if entity.nil? solr_document[workflow_role_field] = workflow_roles(entity).map { |role| "#{entity.workflow.permission_template.source_id}-#{entity.workflow.name}-#{role}" } solr_document[workflow_state_name_field] = entity.workflow_state.name if entity.workflow_state end
[ "def", "index_workflow_fields", "(", "solr_document", ")", "return", "unless", "object", ".", "persisted?", "entity", "=", "PowerConverter", ".", "convert_to_sipity_entity", "(", "object", ")", "return", "if", "entity", ".", "nil?", "solr_document", "[", "workflow_role_field", "]", "=", "workflow_roles", "(", "entity", ")", ".", "map", "{", "|", "role", "|", "\"#{entity.workflow.permission_template.source_id}-#{entity.workflow.name}-#{role}\"", "}", "solr_document", "[", "workflow_state_name_field", "]", "=", "entity", ".", "workflow_state", ".", "name", "if", "entity", ".", "workflow_state", "end" ]
Write the workflow roles and state so one can see where the document moves to next @param [Hash] solr_document the solr document to add the field to
[ "Write", "the", "workflow", "roles", "and", "state", "so", "one", "can", "see", "where", "the", "document", "moves", "to", "next" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/indexers/hyrax/indexes_workflow.rb#L25-L31
train
samvera/hyrax
app/models/sipity/workflow.rb
Sipity.Workflow.add_workflow_responsibilities
def add_workflow_responsibilities(role, agents) Hyrax::Workflow::PermissionGenerator.call(roles: role, workflow: self, agents: agents) end
ruby
def add_workflow_responsibilities(role, agents) Hyrax::Workflow::PermissionGenerator.call(roles: role, workflow: self, agents: agents) end
[ "def", "add_workflow_responsibilities", "(", "role", ",", "agents", ")", "Hyrax", "::", "Workflow", "::", "PermissionGenerator", ".", "call", "(", "roles", ":", "role", ",", "workflow", ":", "self", ",", "agents", ":", "agents", ")", "end" ]
Give workflow responsibilites to the provided agents for the given role @param [Sipity::Role] role @param [Array<Sipity::Agent>] agents
[ "Give", "workflow", "responsibilites", "to", "the", "provided", "agents", "for", "the", "given", "role" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/sipity/workflow.rb#L74-L78
train
samvera/hyrax
app/models/sipity/workflow.rb
Sipity.Workflow.remove_workflow_responsibilities
def remove_workflow_responsibilities(role, allowed_agents) wf_role = Sipity::WorkflowRole.find_by(workflow: self, role_id: role) wf_role.workflow_responsibilities.where.not(agent: allowed_agents).destroy_all end
ruby
def remove_workflow_responsibilities(role, allowed_agents) wf_role = Sipity::WorkflowRole.find_by(workflow: self, role_id: role) wf_role.workflow_responsibilities.where.not(agent: allowed_agents).destroy_all end
[ "def", "remove_workflow_responsibilities", "(", "role", ",", "allowed_agents", ")", "wf_role", "=", "Sipity", "::", "WorkflowRole", ".", "find_by", "(", "workflow", ":", "self", ",", "role_id", ":", "role", ")", "wf_role", ".", "workflow_responsibilities", ".", "where", ".", "not", "(", "agent", ":", "allowed_agents", ")", ".", "destroy_all", "end" ]
Find any workflow_responsibilities held by agents not in the allowed_agents and remove them @param [Sipity::Role] role @param [Array<Sipity::Agent>] allowed_agents
[ "Find", "any", "workflow_responsibilities", "held", "by", "agents", "not", "in", "the", "allowed_agents", "and", "remove", "them" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/sipity/workflow.rb#L84-L87
train
samvera/hyrax
app/presenters/hyrax/presents_attributes.rb
Hyrax.PresentsAttributes.attribute_to_html
def attribute_to_html(field, options = {}) unless respond_to?(field) Rails.logger.warn("#{self.class} attempted to render #{field}, but no method exists with that name.") return end if options[:html_dl] renderer_for(field, options).new(field, send(field), options).render_dl_row else renderer_for(field, options).new(field, send(field), options).render end end
ruby
def attribute_to_html(field, options = {}) unless respond_to?(field) Rails.logger.warn("#{self.class} attempted to render #{field}, but no method exists with that name.") return end if options[:html_dl] renderer_for(field, options).new(field, send(field), options).render_dl_row else renderer_for(field, options).new(field, send(field), options).render end end
[ "def", "attribute_to_html", "(", "field", ",", "options", "=", "{", "}", ")", "unless", "respond_to?", "(", "field", ")", "Rails", ".", "logger", ".", "warn", "(", "\"#{self.class} attempted to render #{field}, but no method exists with that name.\"", ")", "return", "end", "if", "options", "[", ":html_dl", "]", "renderer_for", "(", "field", ",", "options", ")", ".", "new", "(", "field", ",", "send", "(", "field", ")", ",", "options", ")", ".", "render_dl_row", "else", "renderer_for", "(", "field", ",", "options", ")", ".", "new", "(", "field", ",", "send", "(", "field", ")", ",", "options", ")", ".", "render", "end", "end" ]
Present the attribute as an HTML table row or dl row. @param [Hash] options @option options [Symbol] :render_as use an alternate renderer (e.g., :linked or :linked_attribute to use LinkedAttributeRenderer) @option options [String] :search_field If the method_name of the attribute is different than how the attribute name should appear on the search URL, you can explicitly set the URL's search field name @option options [String] :label The default label for the field if no translation is found @option options [TrueClass, FalseClass] :include_empty should we display a row if there are no values? @option options [String] :work_type name of work type class (e.g., "GenericWork")
[ "Present", "the", "attribute", "as", "an", "HTML", "table", "row", "or", "dl", "row", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/presents_attributes.rb#L15-L26
train
samvera/hyrax
app/indexers/hyrax/deep_indexing_service.rb
Hyrax.DeepIndexingService.append_to_solr_doc
def append_to_solr_doc(solr_doc, solr_field_key, field_info, val) return super unless object.controlled_properties.include?(solr_field_key.to_sym) case val when ActiveTriples::Resource append_label_and_uri(solr_doc, solr_field_key, field_info, val) when String append_label(solr_doc, solr_field_key, field_info, val) else raise ArgumentError, "Can't handle #{val.class}" end end
ruby
def append_to_solr_doc(solr_doc, solr_field_key, field_info, val) return super unless object.controlled_properties.include?(solr_field_key.to_sym) case val when ActiveTriples::Resource append_label_and_uri(solr_doc, solr_field_key, field_info, val) when String append_label(solr_doc, solr_field_key, field_info, val) else raise ArgumentError, "Can't handle #{val.class}" end end
[ "def", "append_to_solr_doc", "(", "solr_doc", ",", "solr_field_key", ",", "field_info", ",", "val", ")", "return", "super", "unless", "object", ".", "controlled_properties", ".", "include?", "(", "solr_field_key", ".", "to_sym", ")", "case", "val", "when", "ActiveTriples", "::", "Resource", "append_label_and_uri", "(", "solr_doc", ",", "solr_field_key", ",", "field_info", ",", "val", ")", "when", "String", "append_label", "(", "solr_doc", ",", "solr_field_key", ",", "field_info", ",", "val", ")", "else", "raise", "ArgumentError", ",", "\"Can't handle #{val.class}\"", "end", "end" ]
We're overiding the default indexer in order to index the RDF labels. In order for this to be called, you must specify at least one default indexer on the property. @param [Hash] solr_doc @param [String] solr_field_key @param [Hash] field_info @param [ActiveTriples::Resource, String] val
[ "We", "re", "overiding", "the", "default", "indexer", "in", "order", "to", "index", "the", "RDF", "labels", ".", "In", "order", "for", "this", "to", "be", "called", "you", "must", "specify", "at", "least", "one", "default", "indexer", "on", "the", "property", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/indexers/hyrax/deep_indexing_service.rb#L10-L20
train
samvera/hyrax
app/indexers/hyrax/deep_indexing_service.rb
Hyrax.DeepIndexingService.fetch_external
def fetch_external object.controlled_properties.each do |property| object[property].each do |value| resource = value.respond_to?(:resource) ? value.resource : value next unless resource.is_a?(ActiveTriples::Resource) next if value.is_a?(ActiveFedora::Base) fetch_with_persistence(resource) end end end
ruby
def fetch_external object.controlled_properties.each do |property| object[property].each do |value| resource = value.respond_to?(:resource) ? value.resource : value next unless resource.is_a?(ActiveTriples::Resource) next if value.is_a?(ActiveFedora::Base) fetch_with_persistence(resource) end end end
[ "def", "fetch_external", "object", ".", "controlled_properties", ".", "each", "do", "|", "property", "|", "object", "[", "property", "]", ".", "each", "do", "|", "value", "|", "resource", "=", "value", ".", "respond_to?", "(", ":resource", ")", "?", "value", ".", "resource", ":", "value", "next", "unless", "resource", ".", "is_a?", "(", "ActiveTriples", "::", "Resource", ")", "next", "if", "value", ".", "is_a?", "(", "ActiveFedora", "::", "Base", ")", "fetch_with_persistence", "(", "resource", ")", "end", "end", "end" ]
Grab the labels for controlled properties from the remote sources
[ "Grab", "the", "labels", "for", "controlled", "properties", "from", "the", "remote", "sources" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/indexers/hyrax/deep_indexing_service.rb#L30-L39
train
samvera/hyrax
app/indexers/hyrax/deep_indexing_service.rb
Hyrax.DeepIndexingService.append_label
def append_label(solr_doc, solr_field_key, field_info, val) ActiveFedora::Indexing::Inserter.create_and_insert_terms(solr_field_key, val, field_info.behaviors, solr_doc) ActiveFedora::Indexing::Inserter.create_and_insert_terms("#{solr_field_key}_label", val, field_info.behaviors, solr_doc) end
ruby
def append_label(solr_doc, solr_field_key, field_info, val) ActiveFedora::Indexing::Inserter.create_and_insert_terms(solr_field_key, val, field_info.behaviors, solr_doc) ActiveFedora::Indexing::Inserter.create_and_insert_terms("#{solr_field_key}_label", val, field_info.behaviors, solr_doc) end
[ "def", "append_label", "(", "solr_doc", ",", "solr_field_key", ",", "field_info", ",", "val", ")", "ActiveFedora", "::", "Indexing", "::", "Inserter", ".", "create_and_insert_terms", "(", "solr_field_key", ",", "val", ",", "field_info", ".", "behaviors", ",", "solr_doc", ")", "ActiveFedora", "::", "Indexing", "::", "Inserter", ".", "create_and_insert_terms", "(", "\"#{solr_field_key}_label\"", ",", "val", ",", "field_info", ".", "behaviors", ",", "solr_doc", ")", "end" ]
Use this method to append a string value from a controlled vocabulary field to the solr document. It just puts a copy into the corresponding label field @param [Hash] solr_doc @param [String] solr_field_key @param [Hash] field_info @param [String] val
[ "Use", "this", "method", "to", "append", "a", "string", "value", "from", "a", "controlled", "vocabulary", "field", "to", "the", "solr", "document", ".", "It", "just", "puts", "a", "copy", "into", "the", "corresponding", "label", "field" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/indexers/hyrax/deep_indexing_service.rb#L85-L92
train
samvera/hyrax
app/search_builders/hyrax/deposit_search_builder.rb
Hyrax.DepositSearchBuilder.include_depositor_facet
def include_depositor_facet(solr_parameters) solr_parameters[:"facet.field"].concat([DepositSearchBuilder.depositor_field]) # default facet limit is 10, which will only show the top 10 users. # As we want to show all user deposits, so set the facet.limit to the # the number of users in the database solr_parameters[:"facet.limit"] = ::User.count # we only want the facte counts not the actual data solr_parameters[:rows] = 0 end
ruby
def include_depositor_facet(solr_parameters) solr_parameters[:"facet.field"].concat([DepositSearchBuilder.depositor_field]) # default facet limit is 10, which will only show the top 10 users. # As we want to show all user deposits, so set the facet.limit to the # the number of users in the database solr_parameters[:"facet.limit"] = ::User.count # we only want the facte counts not the actual data solr_parameters[:rows] = 0 end
[ "def", "include_depositor_facet", "(", "solr_parameters", ")", "solr_parameters", "[", ":\"", "\"", "]", ".", "concat", "(", "[", "DepositSearchBuilder", ".", "depositor_field", "]", ")", "solr_parameters", "[", ":\"", "\"", "]", "=", "::", "User", ".", "count", "solr_parameters", "[", ":rows", "]", "=", "0", "end" ]
includes the depositor_facet to get information on deposits. use caution when combining this with other searches as it sets the rows to zero to just get the facet information @param solr_parameters the current solr parameters
[ "includes", "the", "depositor_facet", "to", "get", "information", "on", "deposits", ".", "use", "caution", "when", "combining", "this", "with", "other", "searches", "as", "it", "sets", "the", "rows", "to", "zero", "to", "just", "get", "the", "facet", "information" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/search_builders/hyrax/deposit_search_builder.rb#L7-L17
train
samvera/hyrax
app/controllers/hyrax/users_controller.rb
Hyrax.UsersController.show
def show user = ::User.from_url_component(params[:id]) return redirect_to root_path, alert: "User '#{params[:id]}' does not exist" if user.nil? @presenter = Hyrax::UserProfilePresenter.new(user, current_ability) end
ruby
def show user = ::User.from_url_component(params[:id]) return redirect_to root_path, alert: "User '#{params[:id]}' does not exist" if user.nil? @presenter = Hyrax::UserProfilePresenter.new(user, current_ability) end
[ "def", "show", "user", "=", "::", "User", ".", "from_url_component", "(", "params", "[", ":id", "]", ")", "return", "redirect_to", "root_path", ",", "alert", ":", "\"User '#{params[:id]}' does not exist\"", "if", "user", ".", "nil?", "@presenter", "=", "Hyrax", "::", "UserProfilePresenter", ".", "new", "(", "user", ",", "current_ability", ")", "end" ]
Display user profile
[ "Display", "user", "profile" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/hyrax/users_controller.rb#L14-L18
train
samvera/hyrax
app/presenters/hyrax/presenter_factory.rb
Hyrax.PresenterFactory.query
def query(query, args = {}) args[:q] = query args[:qt] = 'standard' conn = ActiveFedora::SolrService.instance.conn result = conn.post('select', data: args) result.fetch('response').fetch('docs') end
ruby
def query(query, args = {}) args[:q] = query args[:qt] = 'standard' conn = ActiveFedora::SolrService.instance.conn result = conn.post('select', data: args) result.fetch('response').fetch('docs') end
[ "def", "query", "(", "query", ",", "args", "=", "{", "}", ")", "args", "[", ":q", "]", "=", "query", "args", "[", ":qt", "]", "=", "'standard'", "conn", "=", "ActiveFedora", "::", "SolrService", ".", "instance", ".", "conn", "result", "=", "conn", ".", "post", "(", "'select'", ",", "data", ":", "args", ")", "result", ".", "fetch", "(", "'response'", ")", ".", "fetch", "(", "'docs'", ")", "end" ]
Query solr using POST so that the query doesn't get too large for a URI
[ "Query", "solr", "using", "POST", "so", "that", "the", "query", "doesn", "t", "get", "too", "large", "for", "a", "URI" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/presenter_factory.rb#L58-L64
train
samvera/hyrax
lib/hyrax/redis_event_store.rb
Hyrax.RedisEventStore.push
def push(value) RedisEventStore.instance.lpush(@key, value) rescue Redis::CommandError, Redis::CannotConnectError RedisEventStore.logger.error("unable to push event: #{@key}") nil end
ruby
def push(value) RedisEventStore.instance.lpush(@key, value) rescue Redis::CommandError, Redis::CannotConnectError RedisEventStore.logger.error("unable to push event: #{@key}") nil end
[ "def", "push", "(", "value", ")", "RedisEventStore", ".", "instance", ".", "lpush", "(", "@key", ",", "value", ")", "rescue", "Redis", "::", "CommandError", ",", "Redis", "::", "CannotConnectError", "RedisEventStore", ".", "logger", ".", "error", "(", "\"unable to push event: #{@key}\"", ")", "nil", "end" ]
Adds a value to the end of a list identified by key
[ "Adds", "a", "value", "to", "the", "end", "of", "a", "list", "identified", "by", "key" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/lib/hyrax/redis_event_store.rb#L51-L56
train
samvera/hyrax
app/models/hyrax/operation.rb
Hyrax.Operation.rollup_messages
def rollup_messages [].tap do |messages| messages << message if message.present? children&.pluck(:message)&.uniq&.each do |child_message| messages << child_message if child_message.present? end end end
ruby
def rollup_messages [].tap do |messages| messages << message if message.present? children&.pluck(:message)&.uniq&.each do |child_message| messages << child_message if child_message.present? end end end
[ "def", "rollup_messages", "[", "]", ".", "tap", "do", "|", "messages", "|", "messages", "<<", "message", "if", "message", ".", "present?", "children", "&.", "pluck", "(", ":message", ")", "&.", "uniq", "&.", "each", "do", "|", "child_message", "|", "messages", "<<", "child_message", "if", "child_message", ".", "present?", "end", "end", "end" ]
Roll up messages for an operation and all of its children
[ "Roll", "up", "messages", "for", "an", "operation", "and", "all", "of", "its", "children" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/hyrax/operation.rb#L45-L52
train
samvera/hyrax
app/models/hyrax/operation.rb
Hyrax.Operation.fail!
def fail!(message = nil) run_callbacks :failure do update(status: FAILURE, message: message) parent&.rollup_status end end
ruby
def fail!(message = nil) run_callbacks :failure do update(status: FAILURE, message: message) parent&.rollup_status end end
[ "def", "fail!", "(", "message", "=", "nil", ")", "run_callbacks", ":failure", "do", "update", "(", "status", ":", "FAILURE", ",", "message", ":", "message", ")", "parent", "&.", "rollup_status", "end", "end" ]
Mark this operation as a FAILURE. If this is a child operation, roll up to the parent any failures. @param [String, nil] message record any failure message @see Hyrax::Operation::FAILURE @see #rollup_status @note This will run any registered :failure callbacks @todo Where are these callbacks defined? Document this
[ "Mark", "this", "operation", "as", "a", "FAILURE", ".", "If", "this", "is", "a", "child", "operation", "roll", "up", "to", "the", "parent", "any", "failures", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/hyrax/operation.rb#L76-L81
train
samvera/hyrax
app/models/hyrax/operation.rb
Hyrax.Operation.pending_job
def pending_job(job) update(job_class: job.class.to_s, job_id: job.job_id, status: Hyrax::Operation::PENDING) end
ruby
def pending_job(job) update(job_class: job.class.to_s, job_id: job.job_id, status: Hyrax::Operation::PENDING) end
[ "def", "pending_job", "(", "job", ")", "update", "(", "job_class", ":", "job", ".", "class", ".", "to_s", ",", "job_id", ":", "job", ".", "job_id", ",", "status", ":", "Hyrax", "::", "Operation", "::", "PENDING", ")", "end" ]
Sets the operation status to PENDING @param [#class, #job_id] job - The job associated with this operation @see Hyrax::Operation::PENDING
[ "Sets", "the", "operation", "status", "to", "PENDING" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/hyrax/operation.rb#L92-L94
train
samvera/hyrax
app/controllers/hyrax/admin/admin_sets_controller.rb
Hyrax.Admin::AdminSetsController.files
def files result = form.select_files.map { |label, id| { id: id, text: label } } render json: result end
ruby
def files result = form.select_files.map { |label, id| { id: id, text: label } } render json: result end
[ "def", "files", "result", "=", "form", ".", "select_files", ".", "map", "{", "|", "label", ",", "id", "|", "{", "id", ":", "id", ",", "text", ":", "label", "}", "}", "render", "json", ":", "result", "end" ]
Renders a JSON response with a list of files in this admin set. This is used by the edit form to populate the thumbnail_id dropdown
[ "Renders", "a", "JSON", "response", "with", "a", "list", "of", "files", "in", "this", "admin", "set", ".", "This", "is", "used", "by", "the", "edit", "form", "to", "populate", "the", "thumbnail_id", "dropdown" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/controllers/hyrax/admin/admin_sets_controller.rb#L61-L64
train
samvera/hyrax
lib/wings/active_fedora_converter.rb
Wings.ActiveFedoraConverter.id
def id id_attr = resource[:id] return id_attr.to_s if id_attr.present? && id_attr.is_a?(::Valkyrie::ID) && !id_attr.blank? return "" unless resource.respond_to?(:alternate_ids) resource.alternate_ids.first.to_s end
ruby
def id id_attr = resource[:id] return id_attr.to_s if id_attr.present? && id_attr.is_a?(::Valkyrie::ID) && !id_attr.blank? return "" unless resource.respond_to?(:alternate_ids) resource.alternate_ids.first.to_s end
[ "def", "id", "id_attr", "=", "resource", "[", ":id", "]", "return", "id_attr", ".", "to_s", "if", "id_attr", ".", "present?", "&&", "id_attr", ".", "is_a?", "(", "::", "Valkyrie", "::", "ID", ")", "&&", "!", "id_attr", ".", "blank?", "return", "\"\"", "unless", "resource", ".", "respond_to?", "(", ":alternate_ids", ")", "resource", ".", "alternate_ids", ".", "first", ".", "to_s", "end" ]
In the context of a Valkyrie resource, prefer to use the id if it is provided and fallback to the first of the alternate_ids. If all else fails then the id hasn't been minted and shouldn't yet be set. @return [String]
[ "In", "the", "context", "of", "a", "Valkyrie", "resource", "prefer", "to", "use", "the", "id", "if", "it", "is", "provided", "and", "fallback", "to", "the", "first", "of", "the", "alternate_ids", ".", "If", "all", "else", "fails", "then", "the", "id", "hasn", "t", "been", "minted", "and", "shouldn", "t", "yet", "be", "set", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/lib/wings/active_fedora_converter.rb#L69-L74
train
samvera/hyrax
lib/wings/active_fedora_converter.rb
Wings.ActiveFedoraConverter.add_access_control_attributes
def add_access_control_attributes(af_object) af_object.visibility = attributes[:visibility] unless attributes[:visibility].blank? af_object.read_users = attributes[:read_users] unless attributes[:read_users].blank? af_object.edit_users = attributes[:edit_users] unless attributes[:edit_users].blank? af_object.read_groups = attributes[:read_groups] unless attributes[:read_groups].blank? af_object.edit_groups = attributes[:edit_groups] unless attributes[:edit_groups].blank? end
ruby
def add_access_control_attributes(af_object) af_object.visibility = attributes[:visibility] unless attributes[:visibility].blank? af_object.read_users = attributes[:read_users] unless attributes[:read_users].blank? af_object.edit_users = attributes[:edit_users] unless attributes[:edit_users].blank? af_object.read_groups = attributes[:read_groups] unless attributes[:read_groups].blank? af_object.edit_groups = attributes[:edit_groups] unless attributes[:edit_groups].blank? end
[ "def", "add_access_control_attributes", "(", "af_object", ")", "af_object", ".", "visibility", "=", "attributes", "[", ":visibility", "]", "unless", "attributes", "[", ":visibility", "]", ".", "blank?", "af_object", ".", "read_users", "=", "attributes", "[", ":read_users", "]", "unless", "attributes", "[", ":read_users", "]", ".", "blank?", "af_object", ".", "edit_users", "=", "attributes", "[", ":edit_users", "]", "unless", "attributes", "[", ":edit_users", "]", ".", "blank?", "af_object", ".", "read_groups", "=", "attributes", "[", ":read_groups", "]", "unless", "attributes", "[", ":read_groups", "]", ".", "blank?", "af_object", ".", "edit_groups", "=", "attributes", "[", ":edit_groups", "]", "unless", "attributes", "[", ":edit_groups", "]", ".", "blank?", "end" ]
Add attributes from resource which aren't AF properties into af_object
[ "Add", "attributes", "from", "resource", "which", "aren", "t", "AF", "properties", "into", "af_object" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/lib/wings/active_fedora_converter.rb#L151-L157
train
samvera/hyrax
app/presenters/hyrax/collection_presenter.rb
Hyrax.CollectionPresenter.managed_access
def managed_access return I18n.t('hyrax.dashboard.my.collection_list.managed_access.manage') if current_ability.can?(:edit, solr_document) return I18n.t('hyrax.dashboard.my.collection_list.managed_access.deposit') if current_ability.can?(:deposit, solr_document) return I18n.t('hyrax.dashboard.my.collection_list.managed_access.view') if current_ability.can?(:read, solr_document) '' end
ruby
def managed_access return I18n.t('hyrax.dashboard.my.collection_list.managed_access.manage') if current_ability.can?(:edit, solr_document) return I18n.t('hyrax.dashboard.my.collection_list.managed_access.deposit') if current_ability.can?(:deposit, solr_document) return I18n.t('hyrax.dashboard.my.collection_list.managed_access.view') if current_ability.can?(:read, solr_document) '' end
[ "def", "managed_access", "return", "I18n", ".", "t", "(", "'hyrax.dashboard.my.collection_list.managed_access.manage'", ")", "if", "current_ability", ".", "can?", "(", ":edit", ",", "solr_document", ")", "return", "I18n", ".", "t", "(", "'hyrax.dashboard.my.collection_list.managed_access.deposit'", ")", "if", "current_ability", ".", "can?", "(", ":deposit", ",", "solr_document", ")", "return", "I18n", ".", "t", "(", "'hyrax.dashboard.my.collection_list.managed_access.view'", ")", "if", "current_ability", ".", "can?", "(", ":read", ",", "solr_document", ")", "''", "end" ]
For the Managed Collections tab, determine the label to use for the level of access the user has for this admin set. Checks from most permissive to most restrictive. @return String the access label (e.g. Manage, Deposit, View)
[ "For", "the", "Managed", "Collections", "tab", "determine", "the", "label", "to", "use", "for", "the", "level", "of", "access", "the", "user", "has", "for", "this", "admin", "set", ".", "Checks", "from", "most", "permissive", "to", "most", "restrictive", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/collection_presenter.rb#L166-L171
train
samvera/hyrax
app/models/hyrax/collection_type.rb
Hyrax.CollectionType.gid
def gid URI::GID.build(app: GlobalID.app, model_name: model_name.name.parameterize.to_sym, model_id: id).to_s if id end
ruby
def gid URI::GID.build(app: GlobalID.app, model_name: model_name.name.parameterize.to_sym, model_id: id).to_s if id end
[ "def", "gid", "URI", "::", "GID", ".", "build", "(", "app", ":", "GlobalID", ".", "app", ",", "model_name", ":", "model_name", ".", "name", ".", "parameterize", ".", "to_sym", ",", "model_id", ":", "id", ")", ".", "to_s", "if", "id", "end" ]
Return the Global Identifier for this collection type. @return [String] Global Identifier (gid) for this collection_type (e.g. gid://internal/hyrax-collectiontype/3)
[ "Return", "the", "Global", "Identifier", "for", "this", "collection", "type", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/hyrax/collection_type.rb#L58-L60
train
samvera/hyrax
app/models/hyrax/permission_template.rb
Hyrax.PermissionTemplate.release_date
def release_date # If no release delays allowed, return today's date as release date return Time.zone.today if release_no_delay? # If this isn't an embargo, just return release_date from database return self[:release_date] unless release_max_embargo? # Otherwise (if an embargo), return latest embargo date by adding specified months to today's date Time.zone.today + RELEASE_EMBARGO_PERIODS.fetch(release_period).months end
ruby
def release_date # If no release delays allowed, return today's date as release date return Time.zone.today if release_no_delay? # If this isn't an embargo, just return release_date from database return self[:release_date] unless release_max_embargo? # Otherwise (if an embargo), return latest embargo date by adding specified months to today's date Time.zone.today + RELEASE_EMBARGO_PERIODS.fetch(release_period).months end
[ "def", "release_date", "return", "Time", ".", "zone", ".", "today", "if", "release_no_delay?", "return", "self", "[", ":release_date", "]", "unless", "release_max_embargo?", "Time", ".", "zone", ".", "today", "+", "RELEASE_EMBARGO_PERIODS", ".", "fetch", "(", "release_period", ")", ".", "months", "end" ]
Override release_date getter to return a dynamically calculated date of release based one release requirements. Returns embargo date when release_max_embargo?==true. Returns today's date when release_no_delay?==true. @see Hyrax::AdminSetService for usage
[ "Override", "release_date", "getter", "to", "return", "a", "dynamically", "calculated", "date", "of", "release", "based", "one", "release", "requirements", ".", "Returns", "embargo", "date", "when", "release_max_embargo?", "==", "true", ".", "Returns", "today", "s", "date", "when", "release_no_delay?", "==", "true", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/hyrax/permission_template.rb#L109-L118
train
samvera/hyrax
app/models/concerns/hyrax/ability.rb
Hyrax.Ability.download_users
def download_users(id) doc = permissions_doc(id) return [] if doc.nil? users = Array(doc[self.class.read_user_field]) + Array(doc[self.class.edit_user_field]) Rails.logger.debug("[CANCAN] download_users: #{users.inspect}") users end
ruby
def download_users(id) doc = permissions_doc(id) return [] if doc.nil? users = Array(doc[self.class.read_user_field]) + Array(doc[self.class.edit_user_field]) Rails.logger.debug("[CANCAN] download_users: #{users.inspect}") users end
[ "def", "download_users", "(", "id", ")", "doc", "=", "permissions_doc", "(", "id", ")", "return", "[", "]", "if", "doc", ".", "nil?", "users", "=", "Array", "(", "doc", "[", "self", ".", "class", ".", "read_user_field", "]", ")", "+", "Array", "(", "doc", "[", "self", ".", "class", ".", "edit_user_field", "]", ")", "Rails", ".", "logger", ".", "debug", "(", "\"[CANCAN] download_users: #{users.inspect}\"", ")", "users", "end" ]
Grant all users with read or edit access permission to download
[ "Grant", "all", "users", "with", "read", "or", "edit", "access", "permission", "to", "download" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/concerns/hyrax/ability.rb#L47-L53
train
samvera/hyrax
app/models/concerns/hyrax/ability.rb
Hyrax.Ability.trophy_abilities
def trophy_abilities can [:create, :destroy], Trophy do |t| doc = ActiveFedora::Base.search_by_id(t.work_id, fl: 'depositor_ssim') current_user.user_key == doc.fetch('depositor_ssim').first end end
ruby
def trophy_abilities can [:create, :destroy], Trophy do |t| doc = ActiveFedora::Base.search_by_id(t.work_id, fl: 'depositor_ssim') current_user.user_key == doc.fetch('depositor_ssim').first end end
[ "def", "trophy_abilities", "can", "[", ":create", ",", ":destroy", "]", ",", "Trophy", "do", "|", "t", "|", "doc", "=", "ActiveFedora", "::", "Base", ".", "search_by_id", "(", "t", ".", "work_id", ",", "fl", ":", "'depositor_ssim'", ")", "current_user", ".", "user_key", "==", "doc", ".", "fetch", "(", "'depositor_ssim'", ")", ".", "first", "end", "end" ]
We check based on the depositor, because the depositor may not have edit access to the work if it went through a mediated deposit workflow that removes edit access for the depositor.
[ "We", "check", "based", "on", "the", "depositor", "because", "the", "depositor", "may", "not", "have", "edit", "access", "to", "the", "work", "if", "it", "went", "through", "a", "mediated", "deposit", "workflow", "that", "removes", "edit", "access", "for", "the", "depositor", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/concerns/hyrax/ability.rb#L162-L167
train
samvera/hyrax
app/models/concerns/hyrax/ability.rb
Hyrax.Ability.user_is_depositor?
def user_is_depositor?(document_id) Hyrax::WorkRelation.new.search_with_conditions( id: document_id, DepositSearchBuilder.depositor_field => current_user.user_key ).any? end
ruby
def user_is_depositor?(document_id) Hyrax::WorkRelation.new.search_with_conditions( id: document_id, DepositSearchBuilder.depositor_field => current_user.user_key ).any? end
[ "def", "user_is_depositor?", "(", "document_id", ")", "Hyrax", "::", "WorkRelation", ".", "new", ".", "search_with_conditions", "(", "id", ":", "document_id", ",", "DepositSearchBuilder", ".", "depositor_field", "=>", "current_user", ".", "user_key", ")", ".", "any?", "end" ]
Returns true if the current user is the depositor of the specified work @param document_id [String] the id of the document.
[ "Returns", "true", "if", "the", "current", "user", "is", "the", "depositor", "of", "the", "specified", "work" ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/models/concerns/hyrax/ability.rb#L207-L212
train
samvera/hyrax
app/presenters/hyrax/characterization_behavior.rb
Hyrax.CharacterizationBehavior.primary_characterization_values
def primary_characterization_values(term) values = values_for(term) values.slice!(Hyrax.config.fits_message_length, (values.length - Hyrax.config.fits_message_length)) truncate_all(values) end
ruby
def primary_characterization_values(term) values = values_for(term) values.slice!(Hyrax.config.fits_message_length, (values.length - Hyrax.config.fits_message_length)) truncate_all(values) end
[ "def", "primary_characterization_values", "(", "term", ")", "values", "=", "values_for", "(", "term", ")", "values", ".", "slice!", "(", "Hyrax", ".", "config", ".", "fits_message_length", ",", "(", "values", ".", "length", "-", "Hyrax", ".", "config", ".", "fits_message_length", ")", ")", "truncate_all", "(", "values", ")", "end" ]
Returns an array of characterization values truncated to 250 characters limited to the maximum number of configured values. @param [Symbol] term found in the characterization_metadata hash @return [Array] of truncated values
[ "Returns", "an", "array", "of", "characterization", "values", "truncated", "to", "250", "characters", "limited", "to", "the", "maximum", "number", "of", "configured", "values", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/characterization_behavior.rb#L49-L53
train
samvera/hyrax
app/presenters/hyrax/characterization_behavior.rb
Hyrax.CharacterizationBehavior.secondary_characterization_values
def secondary_characterization_values(term) values = values_for(term) additional_values = values.slice(Hyrax.config.fits_message_length, values.length - Hyrax.config.fits_message_length) return [] unless additional_values truncate_all(additional_values) end
ruby
def secondary_characterization_values(term) values = values_for(term) additional_values = values.slice(Hyrax.config.fits_message_length, values.length - Hyrax.config.fits_message_length) return [] unless additional_values truncate_all(additional_values) end
[ "def", "secondary_characterization_values", "(", "term", ")", "values", "=", "values_for", "(", "term", ")", "additional_values", "=", "values", ".", "slice", "(", "Hyrax", ".", "config", ".", "fits_message_length", ",", "values", ".", "length", "-", "Hyrax", ".", "config", ".", "fits_message_length", ")", "return", "[", "]", "unless", "additional_values", "truncate_all", "(", "additional_values", ")", "end" ]
Returns an array of characterization values truncated to 250 characters that are in excess of the maximum number of configured values. @param [Symbol] term found in the characterization_metadata hash @return [Array] of truncated values
[ "Returns", "an", "array", "of", "characterization", "values", "truncated", "to", "250", "characters", "that", "are", "in", "excess", "of", "the", "maximum", "number", "of", "configured", "values", "." ]
e2b4f56e829a53b1f11296324736e9d5b8c9ee5f
https://github.com/samvera/hyrax/blob/e2b4f56e829a53b1f11296324736e9d5b8c9ee5f/app/presenters/hyrax/characterization_behavior.rb#L59-L64
train
hexgnu/linkedin
lib/linked_in/search.rb
LinkedIn.Search.search
def search(options={}, type='people') path = "/#{type.to_s}-search" if options.is_a?(Hash) fields = options.delete(:fields) path += field_selector(fields) if fields end options = { :keywords => options } if options.is_a?(String) options = format_options_for_query(options) result_json = get(to_uri(path, options)) Mash.from_json(result_json) end
ruby
def search(options={}, type='people') path = "/#{type.to_s}-search" if options.is_a?(Hash) fields = options.delete(:fields) path += field_selector(fields) if fields end options = { :keywords => options } if options.is_a?(String) options = format_options_for_query(options) result_json = get(to_uri(path, options)) Mash.from_json(result_json) end
[ "def", "search", "(", "options", "=", "{", "}", ",", "type", "=", "'people'", ")", "path", "=", "\"/#{type.to_s}-search\"", "if", "options", ".", "is_a?", "(", "Hash", ")", "fields", "=", "options", ".", "delete", "(", ":fields", ")", "path", "+=", "field_selector", "(", "fields", ")", "if", "fields", "end", "options", "=", "{", ":keywords", "=>", "options", "}", "if", "options", ".", "is_a?", "(", "String", ")", "options", "=", "format_options_for_query", "(", "options", ")", "result_json", "=", "get", "(", "to_uri", "(", "path", ",", "options", ")", ")", "Mash", ".", "from_json", "(", "result_json", ")", "end" ]
Retrieve search results of the given object type Permissions: (for people search only) r_network @note People Search API is a part of the Vetted API Access Program. You must apply and get approval before using this API @see http://developer.linkedin.com/documents/people-search-api People Search @see http://developer.linkedin.com/documents/job-search-api Job Search @see http://developer.linkedin.com/documents/company-search Company Search @param [Hash] options search input fields @param [String] type type of object to return ('people', 'job' or 'company') @return [LinkedIn::Mash]
[ "Retrieve", "search", "results", "of", "the", "given", "object", "type" ]
a56f5381e7d84b934c53e891b1f0421fe8a6caf9
https://github.com/hexgnu/linkedin/blob/a56f5381e7d84b934c53e891b1f0421fe8a6caf9/lib/linked_in/search.rb#L19-L34
train
hexgnu/linkedin
lib/linked_in/mash.rb
LinkedIn.Mash.timestamp
def timestamp value = self['timestamp'] if value.kind_of? Integer value = value / 1000 if value > 9999999999 Time.at(value) else value end end
ruby
def timestamp value = self['timestamp'] if value.kind_of? Integer value = value / 1000 if value > 9999999999 Time.at(value) else value end end
[ "def", "timestamp", "value", "=", "self", "[", "'timestamp'", "]", "if", "value", ".", "kind_of?", "Integer", "value", "=", "value", "/", "1000", "if", "value", ">", "9999999999", "Time", ".", "at", "(", "value", ")", "else", "value", "end", "end" ]
Convert the 'timestamp' field from a string to a Time object @return [Time]
[ "Convert", "the", "timestamp", "field", "from", "a", "string", "to", "a", "Time", "object" ]
a56f5381e7d84b934c53e891b1f0421fe8a6caf9
https://github.com/hexgnu/linkedin/blob/a56f5381e7d84b934c53e891b1f0421fe8a6caf9/lib/linked_in/mash.rb#L44-L52
train
librariesio/bibliothecary
lib/bibliothecary/runner.rb
Bibliothecary.Runner.identify_manifests
def identify_manifests(file_list) ignored_dirs_with_slash = ignored_dirs.map { |d| if d.end_with?("/") then d else d + "/" end } allowed_file_list = file_list.reject do |f| ignored_dirs.include?(f) || f.start_with?(*ignored_dirs_with_slash) end allowed_file_list = allowed_file_list.reject{|f| ignored_files.include?(f)} package_managers.map do |pm| allowed_file_list.select do |file_path| # this is a call to match? without file contents, which will skip # ambiguous filenames that are only possibly a manifest pm.match?(file_path) end end.flatten.uniq.compact end
ruby
def identify_manifests(file_list) ignored_dirs_with_slash = ignored_dirs.map { |d| if d.end_with?("/") then d else d + "/" end } allowed_file_list = file_list.reject do |f| ignored_dirs.include?(f) || f.start_with?(*ignored_dirs_with_slash) end allowed_file_list = allowed_file_list.reject{|f| ignored_files.include?(f)} package_managers.map do |pm| allowed_file_list.select do |file_path| # this is a call to match? without file contents, which will skip # ambiguous filenames that are only possibly a manifest pm.match?(file_path) end end.flatten.uniq.compact end
[ "def", "identify_manifests", "(", "file_list", ")", "ignored_dirs_with_slash", "=", "ignored_dirs", ".", "map", "{", "|", "d", "|", "if", "d", ".", "end_with?", "(", "\"/\"", ")", "then", "d", "else", "d", "+", "\"/\"", "end", "}", "allowed_file_list", "=", "file_list", ".", "reject", "do", "|", "f", "|", "ignored_dirs", ".", "include?", "(", "f", ")", "||", "f", ".", "start_with?", "(", "*", "ignored_dirs_with_slash", ")", "end", "allowed_file_list", "=", "allowed_file_list", ".", "reject", "{", "|", "f", "|", "ignored_files", ".", "include?", "(", "f", ")", "}", "package_managers", ".", "map", "do", "|", "pm", "|", "allowed_file_list", ".", "select", "do", "|", "file_path", "|", "pm", ".", "match?", "(", "file_path", ")", "end", "end", ".", "flatten", ".", "uniq", ".", "compact", "end" ]
this skips manifests sometimes because it doesn't look at file contents and can't establish from only regexes that the thing is a manifest. We exclude rather than include ambiguous filenames because this API is used by libraries.io and we don't want to download all .xml files from GitHub.
[ "this", "skips", "manifests", "sometimes", "because", "it", "doesn", "t", "look", "at", "file", "contents", "and", "can", "t", "establish", "from", "only", "regexes", "that", "the", "thing", "is", "a", "manifest", ".", "We", "exclude", "rather", "than", "include", "ambiguous", "filenames", "because", "this", "API", "is", "used", "by", "libraries", ".", "io", "and", "we", "don", "t", "want", "to", "download", "all", ".", "xml", "files", "from", "GitHub", "." ]
c446640356d5d57ceebfd27327aecd1ef7a3cd01
https://github.com/librariesio/bibliothecary/blob/c446640356d5d57ceebfd27327aecd1ef7a3cd01/lib/bibliothecary/runner.rb#L79-L92
train
square/connect-ruby-sdk
lib/square_connect/models/create_order_request.rb
SquareConnect.CreateOrderRequest.to_hash
def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end
ruby
def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end
[ "def", "to_hash", "hash", "=", "{", "}", "self", ".", "class", ".", "attribute_map", ".", "each_pair", "do", "|", "attr", ",", "param", "|", "value", "=", "self", ".", "send", "(", "attr", ")", "next", "if", "value", ".", "nil?", "hash", "[", "param", "]", "=", "_to_hash", "(", "value", ")", "end", "hash", "end" ]
Returns the object in the form of hash @return [Hash] Returns the object in the form of hash
[ "Returns", "the", "object", "in", "the", "form", "of", "hash" ]
798eb9ded716f23b9f1518386f1c311a34bca8bf
https://github.com/square/connect-ruby-sdk/blob/798eb9ded716f23b9f1518386f1c311a34bca8bf/lib/square_connect/models/create_order_request.rb#L244-L252
train
square/connect-ruby-sdk
lib/square_connect/models/create_order_request.rb
SquareConnect.CreateOrderRequest._to_hash
def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end
ruby
def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end
[ "def", "_to_hash", "(", "value", ")", "if", "value", ".", "is_a?", "(", "Array", ")", "value", ".", "compact", ".", "map", "{", "|", "v", "|", "_to_hash", "(", "v", ")", "}", "elsif", "value", ".", "is_a?", "(", "Hash", ")", "{", "}", ".", "tap", "do", "|", "hash", "|", "value", ".", "each", "{", "|", "k", ",", "v", "|", "hash", "[", "k", "]", "=", "_to_hash", "(", "v", ")", "}", "end", "elsif", "value", ".", "respond_to?", ":to_hash", "value", ".", "to_hash", "else", "value", "end", "end" ]
Outputs non-array value in the form of hash For object, use to_hash. Otherwise, just return the value @param [Object] value Any valid value @return [Hash] Returns the value in the form of hash
[ "Outputs", "non", "-", "array", "value", "in", "the", "form", "of", "hash", "For", "object", "use", "to_hash", ".", "Otherwise", "just", "return", "the", "value" ]
798eb9ded716f23b9f1518386f1c311a34bca8bf
https://github.com/square/connect-ruby-sdk/blob/798eb9ded716f23b9f1518386f1c311a34bca8bf/lib/square_connect/models/create_order_request.rb#L258-L270
train
square/connect-ruby-sdk
lib/square_connect/api_client.rb
SquareConnect.ApiClient.get_v1_batch_token_from_headers
def get_v1_batch_token_from_headers(headers) if headers.is_a?(Hash) && headers.has_key?('Link') match = /^<([^>]+)>;rel='next'$/.match(headers['Link']) if match uri = URI.parse(match[1]) params = CGI.parse(uri.query) return params['batch_token'][0] end end end
ruby
def get_v1_batch_token_from_headers(headers) if headers.is_a?(Hash) && headers.has_key?('Link') match = /^<([^>]+)>;rel='next'$/.match(headers['Link']) if match uri = URI.parse(match[1]) params = CGI.parse(uri.query) return params['batch_token'][0] end end end
[ "def", "get_v1_batch_token_from_headers", "(", "headers", ")", "if", "headers", ".", "is_a?", "(", "Hash", ")", "&&", "headers", ".", "has_key?", "(", "'Link'", ")", "match", "=", "/", "/", ".", "match", "(", "headers", "[", "'Link'", "]", ")", "if", "match", "uri", "=", "URI", ".", "parse", "(", "match", "[", "1", "]", ")", "params", "=", "CGI", ".", "parse", "(", "uri", ".", "query", ")", "return", "params", "[", "'batch_token'", "]", "[", "0", "]", "end", "end", "end" ]
Extract batch_token from Link header if present @param [Hash] headers hash with response headers @return [String] batch_token or nil if no token is present
[ "Extract", "batch_token", "from", "Link", "header", "if", "present" ]
798eb9ded716f23b9f1518386f1c311a34bca8bf
https://github.com/square/connect-ruby-sdk/blob/798eb9ded716f23b9f1518386f1c311a34bca8bf/lib/square_connect/api_client.rb#L388-L397
train
square/connect-ruby-sdk
lib/square_connect/api/v1_employees_api.rb
SquareConnect.V1EmployeesApi.list_cash_drawer_shifts
def list_cash_drawer_shifts(location_id, opts = {}) data, _status_code, _headers = list_cash_drawer_shifts_with_http_info(location_id, opts) return data end
ruby
def list_cash_drawer_shifts(location_id, opts = {}) data, _status_code, _headers = list_cash_drawer_shifts_with_http_info(location_id, opts) return data end
[ "def", "list_cash_drawer_shifts", "(", "location_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "list_cash_drawer_shifts_with_http_info", "(", "location_id", ",", "opts", ")", "return", "data", "end" ]
ListCashDrawerShifts Provides the details for all of a location's cash drawer shifts during a date range. The date range you specify cannot exceed 90 days. @param location_id The ID of the location to list cash drawer shifts for. @param [Hash] opts the optional parameters @option opts [String] :order The order in which cash drawer shifts are listed in the response, based on their created_at field. Default value: ASC @option opts [String] :begin_time The beginning of the requested reporting period, in ISO 8601 format. Default value: The current time minus 90 days. @option opts [String] :end_time The beginning of the requested reporting period, in ISO 8601 format. Default value: The current time. @return [Array<V1CashDrawerShift>]
[ "ListCashDrawerShifts", "Provides", "the", "details", "for", "all", "of", "a", "location", "s", "cash", "drawer", "shifts", "during", "a", "date", "range", ".", "The", "date", "range", "you", "specify", "cannot", "exceed", "90", "days", "." ]
798eb9ded716f23b9f1518386f1c311a34bca8bf
https://github.com/square/connect-ruby-sdk/blob/798eb9ded716f23b9f1518386f1c311a34bca8bf/lib/square_connect/api/v1_employees_api.rb#L248-L251
train