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 |
---|---|---|---|---|---|---|---|---|---|---|---|
david942j/heapinfo | lib/heapinfo/libc.rb | HeapInfo.Libc.main_arena | def main_arena
return @main_arena.reload! if defined? @main_arena
off = main_arena_offset
return if off.nil?
@main_arena = Arena.new(off + base, size_t, dumper)
end | ruby | def main_arena
return @main_arena.reload! if defined? @main_arena
off = main_arena_offset
return if off.nil?
@main_arena = Arena.new(off + base, size_t, dumper)
end | [
"def",
"main_arena",
"return",
"@main_arena",
".",
"reload!",
"if",
"defined?",
"@main_arena",
"off",
"=",
"main_arena_offset",
"return",
"if",
"off",
".",
"nil?",
"@main_arena",
"=",
"Arena",
".",
"new",
"(",
"off",
"+",
"base",
",",
"size_t",
",",
"dumper",
")",
"end"
] | Get the +main_arena+ of libc.
@return [HeapInfo::Arena] | [
"Get",
"the",
"+",
"main_arena",
"+",
"of",
"libc",
"."
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/libc.rb#L30-L37 | train |
david942j/heapinfo | lib/heapinfo/libc.rb | HeapInfo.Libc.info | def info
return @info if defined? @info
# Try to fetch from cache first.
key = HeapInfo::Cache.key_libc_info(name)
@info = HeapInfo::Cache.read(key)
@info ||= execute_libc_info.tap { |i| HeapInfo::Cache.write(key, i) }
end | ruby | def info
return @info if defined? @info
# Try to fetch from cache first.
key = HeapInfo::Cache.key_libc_info(name)
@info = HeapInfo::Cache.read(key)
@info ||= execute_libc_info.tap { |i| HeapInfo::Cache.write(key, i) }
end | [
"def",
"info",
"return",
"@info",
"if",
"defined?",
"@info",
"# Try to fetch from cache first.",
"key",
"=",
"HeapInfo",
"::",
"Cache",
".",
"key_libc_info",
"(",
"name",
")",
"@info",
"=",
"HeapInfo",
"::",
"Cache",
".",
"read",
"(",
"key",
")",
"@info",
"||=",
"execute_libc_info",
".",
"tap",
"{",
"|",
"i",
"|",
"HeapInfo",
"::",
"Cache",
".",
"write",
"(",
"key",
",",
"i",
")",
"}",
"end"
] | Get libc's info. | [
"Get",
"libc",
"s",
"info",
"."
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/libc.rb#L79-L86 | train |
david942j/heapinfo | lib/heapinfo/nil.rb | HeapInfo.Nil.method_missing | def method_missing(method_sym, *args, &block) # rubocop:disable Style/MethodMissingSuper
return nil.__send__(method_sym, *args, &block) if nil.respond_to?(method_sym)
self
end | ruby | def method_missing(method_sym, *args, &block) # rubocop:disable Style/MethodMissingSuper
return nil.__send__(method_sym, *args, &block) if nil.respond_to?(method_sym)
self
end | [
"def",
"method_missing",
"(",
"method_sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"# rubocop:disable Style/MethodMissingSuper",
"return",
"nil",
".",
"__send__",
"(",
"method_sym",
",",
"args",
",",
"block",
")",
"if",
"nil",
".",
"respond_to?",
"(",
"method_sym",
")",
"self",
"end"
] | Hook all missing methods
@return [HeapInfo::Nil] return +self+ so that it can be a +nil+ chain.
@example
# h.dump would return Nil when process not found
p h.dump(:heap)[8, 8].unpack('Q*')
#=> nil | [
"Hook",
"all",
"missing",
"methods"
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/nil.rb#L21-L25 | train |
david942j/heapinfo | lib/heapinfo/glibc/free.rb | HeapInfo.Glibc.invalid_pointer | def invalid_pointer(ptr, size)
errmsg = "free(): invalid pointer\n"
# unsigned compare
malloc_assert(ptr <= ulong(-size)) { errmsg + format('ptr(0x%x) > -size(0x%x)', ptr, ulong(-size)) }
malloc_assert((ptr % (size_t * 2)).zero?) { errmsg + format('ptr(0x%x) %% %d != 0', ptr, size_t * 2) }
end | ruby | def invalid_pointer(ptr, size)
errmsg = "free(): invalid pointer\n"
# unsigned compare
malloc_assert(ptr <= ulong(-size)) { errmsg + format('ptr(0x%x) > -size(0x%x)', ptr, ulong(-size)) }
malloc_assert((ptr % (size_t * 2)).zero?) { errmsg + format('ptr(0x%x) %% %d != 0', ptr, size_t * 2) }
end | [
"def",
"invalid_pointer",
"(",
"ptr",
",",
"size",
")",
"errmsg",
"=",
"\"free(): invalid pointer\\n\"",
"# unsigned compare",
"malloc_assert",
"(",
"ptr",
"<=",
"ulong",
"(",
"-",
"size",
")",
")",
"{",
"errmsg",
"+",
"format",
"(",
"'ptr(0x%x) > -size(0x%x)'",
",",
"ptr",
",",
"ulong",
"(",
"-",
"size",
")",
")",
"}",
"malloc_assert",
"(",
"(",
"ptr",
"%",
"(",
"size_t",
"*",
"2",
")",
")",
".",
"zero?",
")",
"{",
"errmsg",
"+",
"format",
"(",
"'ptr(0x%x) %% %d != 0'",
",",
"ptr",
",",
"size_t",
"*",
"2",
")",
"}",
"end"
] | Start of checkers | [
"Start",
"of",
"checkers"
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/glibc/free.rb#L67-L72 | train |
david942j/heapinfo | lib/heapinfo/chunk.rb | HeapInfo.Chunk.flags | def flags
mask = @size - size
flag = []
flag << :non_main_arena unless (mask & 4).zero?
flag << :mmapped unless (mask & 2).zero?
flag << :prev_inuse unless (mask & 1).zero?
flag
end | ruby | def flags
mask = @size - size
flag = []
flag << :non_main_arena unless (mask & 4).zero?
flag << :mmapped unless (mask & 2).zero?
flag << :prev_inuse unless (mask & 1).zero?
flag
end | [
"def",
"flags",
"mask",
"=",
"@size",
"-",
"size",
"flag",
"=",
"[",
"]",
"flag",
"<<",
":non_main_arena",
"unless",
"(",
"mask",
"&",
"4",
")",
".",
"zero?",
"flag",
"<<",
":mmapped",
"unless",
"(",
"mask",
"&",
"2",
")",
".",
"zero?",
"flag",
"<<",
":prev_inuse",
"unless",
"(",
"mask",
"&",
"1",
")",
".",
"zero?",
"flag",
"end"
] | The chunk flags record in low three bits of size
@return [Array<Symbol>] flags of chunk
@example
c = [0, 0x25].pack("Q*").to_chunk
c.flags
# [:non_main_arena, :prev_inuse] | [
"The",
"chunk",
"flags",
"record",
"in",
"low",
"three",
"bits",
"of",
"size"
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/chunk.rb#L61-L68 | train |
david942j/heapinfo | lib/heapinfo/process.rb | HeapInfo.Process.offset | def offset(addr, sym = nil)
return unless load?
segment = @info.to_segment(sym)
if segment.nil?
sym, segment = @info.segments
.select { |_, seg| seg.base <= addr }
.min_by { |_, seg| addr - seg }
end
return $stdout.puts "Invalid address #{Helper.hex(addr)}" if segment.nil?
$stdout.puts Helper.color(Helper.hex(addr - segment)) + ' after ' + Helper.color(sym, sev: :sym)
end | ruby | def offset(addr, sym = nil)
return unless load?
segment = @info.to_segment(sym)
if segment.nil?
sym, segment = @info.segments
.select { |_, seg| seg.base <= addr }
.min_by { |_, seg| addr - seg }
end
return $stdout.puts "Invalid address #{Helper.hex(addr)}" if segment.nil?
$stdout.puts Helper.color(Helper.hex(addr - segment)) + ' after ' + Helper.color(sym, sev: :sym)
end | [
"def",
"offset",
"(",
"addr",
",",
"sym",
"=",
"nil",
")",
"return",
"unless",
"load?",
"segment",
"=",
"@info",
".",
"to_segment",
"(",
"sym",
")",
"if",
"segment",
".",
"nil?",
"sym",
",",
"segment",
"=",
"@info",
".",
"segments",
".",
"select",
"{",
"|",
"_",
",",
"seg",
"|",
"seg",
".",
"base",
"<=",
"addr",
"}",
".",
"min_by",
"{",
"|",
"_",
",",
"seg",
"|",
"addr",
"-",
"seg",
"}",
"end",
"return",
"$stdout",
".",
"puts",
"\"Invalid address #{Helper.hex(addr)}\"",
"if",
"segment",
".",
"nil?",
"$stdout",
".",
"puts",
"Helper",
".",
"color",
"(",
"Helper",
".",
"hex",
"(",
"addr",
"-",
"segment",
")",
")",
"+",
"' after '",
"+",
"Helper",
".",
"color",
"(",
"sym",
",",
"sev",
":",
":sym",
")",
"end"
] | Show the offset in pretty way between the segment.
Very useful in pwn when leak some address,
see examples for more details.
@param [Integer] addr The leaked address.
@param [Symbol] sym
The segement symbol to be calculated offset.
If this parameter not given, will loop segments
and find the most close one. See examples for more details.
@return [void] Offset will show to stdout.
@example
h.offset(0x7f11f6ae1670, :libc)
#=> 0xf6670 after libc
h.offset(0x5559edc057a0, :heap)
#=> 0x9637a0 after heap
h.offset(0x7f11f6ae1670)
#=> 0xf6670 after :libc
h.offset(0x5559edc057a0)
#=> 0x9637a0 after :heap | [
"Show",
"the",
"offset",
"in",
"pretty",
"way",
"between",
"the",
"segment",
".",
"Very",
"useful",
"in",
"pwn",
"when",
"leak",
"some",
"address",
"see",
"examples",
"for",
"more",
"details",
"."
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L128-L140 | train |
david942j/heapinfo | lib/heapinfo/process.rb | HeapInfo.Process.find | def find(pattern, from, length = :unlimited, rel: false)
return Nil.instance unless load?
dumper.find(pattern, from, length, rel)
end | ruby | def find(pattern, from, length = :unlimited, rel: false)
return Nil.instance unless load?
dumper.find(pattern, from, length, rel)
end | [
"def",
"find",
"(",
"pattern",
",",
"from",
",",
"length",
"=",
":unlimited",
",",
"rel",
":",
"false",
")",
"return",
"Nil",
".",
"instance",
"unless",
"load?",
"dumper",
".",
"find",
"(",
"pattern",
",",
"from",
",",
"length",
",",
"rel",
")",
"end"
] | Gdb-like command.
Search a specific value/string/regexp in memory.
@param [Integer, String, Regexp] pattern
The desired search pattern, can be value(+Integer+), string, or regular expression.
@param [Integer, String, Symbol] from
Start address for searching, can be segment(+Symbol+) or segments with offset.
See examples for more information.
@param [Integer] length
The search length limit, default is unlimited,
which will search until pattern found or reach unreadable memory.
@param [Boolean] rel
To show relative offset of +from+ or absolute address.
@return [Integer, nil] The first matched address, +nil+ is returned when no such pattern found.
@example
h.find(0xdeadbeef, 'heap+0x10', 0x1000)
#=> 6299664 # 0x602010
h.find(/E.F/, 0x400000, 4)
#=> 4194305 # 0x400001
h.find(/E.F/, 0x400000, 3)
#=> nil
sh_offset = h.find('/bin/sh', :libc) - h.libc
#=> 1559771 # 0x17ccdb
h.find('/bin/sh', :libc, rel: true) == h.find('/bin/sh', :libc) - h.libc
#=> true | [
"Gdb",
"-",
"like",
"command",
"."
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L208-L212 | train |
david942j/heapinfo | lib/heapinfo/process.rb | HeapInfo.Process.find_all | def find_all(pattern, segment = :all)
return Nil.instance unless load?
segments = segment == :all ? %i[elf heap libc ld stack] : Array(segment)
result = findall_raw(pattern, segments).reject { |(_, _, ary)| ary.empty? }
target = pattern.is_a?(Integer) ? Helper.hex(pattern) : pattern.inspect
str = ["Searching #{Helper.color(target)}:\n"]
str.concat(result.map do |(sym, base, ary)|
"In #{Helper.color(sym, sev: :bin)} (#{Helper.color(Helper.hex(base))}):\n" +
ary.map { |v| " #{Helper.color(sym, sev: :bin)}+#{Helper.color(Helper.hex(v))}\n" }.join
end)
$stdout.puts str
end | ruby | def find_all(pattern, segment = :all)
return Nil.instance unless load?
segments = segment == :all ? %i[elf heap libc ld stack] : Array(segment)
result = findall_raw(pattern, segments).reject { |(_, _, ary)| ary.empty? }
target = pattern.is_a?(Integer) ? Helper.hex(pattern) : pattern.inspect
str = ["Searching #{Helper.color(target)}:\n"]
str.concat(result.map do |(sym, base, ary)|
"In #{Helper.color(sym, sev: :bin)} (#{Helper.color(Helper.hex(base))}):\n" +
ary.map { |v| " #{Helper.color(sym, sev: :bin)}+#{Helper.color(Helper.hex(v))}\n" }.join
end)
$stdout.puts str
end | [
"def",
"find_all",
"(",
"pattern",
",",
"segment",
"=",
":all",
")",
"return",
"Nil",
".",
"instance",
"unless",
"load?",
"segments",
"=",
"segment",
"==",
":all",
"?",
"%i[",
"elf",
"heap",
"libc",
"ld",
"stack",
"]",
":",
"Array",
"(",
"segment",
")",
"result",
"=",
"findall_raw",
"(",
"pattern",
",",
"segments",
")",
".",
"reject",
"{",
"|",
"(",
"_",
",",
"_",
",",
"ary",
")",
"|",
"ary",
".",
"empty?",
"}",
"target",
"=",
"pattern",
".",
"is_a?",
"(",
"Integer",
")",
"?",
"Helper",
".",
"hex",
"(",
"pattern",
")",
":",
"pattern",
".",
"inspect",
"str",
"=",
"[",
"\"Searching #{Helper.color(target)}:\\n\"",
"]",
"str",
".",
"concat",
"(",
"result",
".",
"map",
"do",
"|",
"(",
"sym",
",",
"base",
",",
"ary",
")",
"|",
"\"In #{Helper.color(sym, sev: :bin)} (#{Helper.color(Helper.hex(base))}):\\n\"",
"+",
"ary",
".",
"map",
"{",
"|",
"v",
"|",
"\" #{Helper.color(sym, sev: :bin)}+#{Helper.color(Helper.hex(v))}\\n\"",
"}",
".",
"join",
"end",
")",
"$stdout",
".",
"puts",
"str",
"end"
] | Find pattern in all segments with pretty output.
@param [Integer, String, Regexp] pattern
The desired search pattern, can be value(+Integer+), string, or regular expression.
@param [Symbol, Array<Symbol>] segment
Only find pattern in these symbols.
@return [void] | [
"Find",
"pattern",
"in",
"all",
"segments",
"with",
"pretty",
"output",
"."
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L223-L235 | train |
david942j/heapinfo | lib/heapinfo/process.rb | HeapInfo.Process.to_s | def to_s
return 'Process not found' unless load?
"Program: #{Helper.color(program.name)} PID: #{Helper.color(pid)}\n" +
program.to_s +
heap.to_s +
stack.to_s +
libc.to_s +
ld.to_s +
format("%-28s\tvalue: #{Helper.color(format('%#x', canary), sev: :sym)}", Helper.color('canary', sev: :sym))
end | ruby | def to_s
return 'Process not found' unless load?
"Program: #{Helper.color(program.name)} PID: #{Helper.color(pid)}\n" +
program.to_s +
heap.to_s +
stack.to_s +
libc.to_s +
ld.to_s +
format("%-28s\tvalue: #{Helper.color(format('%#x', canary), sev: :sym)}", Helper.color('canary', sev: :sym))
end | [
"def",
"to_s",
"return",
"'Process not found'",
"unless",
"load?",
"\"Program: #{Helper.color(program.name)} PID: #{Helper.color(pid)}\\n\"",
"+",
"program",
".",
"to_s",
"+",
"heap",
".",
"to_s",
"+",
"stack",
".",
"to_s",
"+",
"libc",
".",
"to_s",
"+",
"ld",
".",
"to_s",
"+",
"format",
"(",
"\"%-28s\\tvalue: #{Helper.color(format('%#x', canary), sev: :sym)}\"",
",",
"Helper",
".",
"color",
"(",
"'canary'",
",",
"sev",
":",
":sym",
")",
")",
"end"
] | Show simple information of target process.
Contains program names, pid, and segments' info.
@return [String]
@example
puts h | [
"Show",
"simple",
"information",
"of",
"target",
"process",
"."
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L266-L276 | train |
david942j/heapinfo | lib/heapinfo/process.rb | HeapInfo.Process.canary | def canary
return Nil.instance unless load?
addr = @info.auxv[:random]
Helper.unpack(bits / 8, @dumper.dump(addr, bits / 8)) & 0xffffffffffffff00
end | ruby | def canary
return Nil.instance unless load?
addr = @info.auxv[:random]
Helper.unpack(bits / 8, @dumper.dump(addr, bits / 8)) & 0xffffffffffffff00
end | [
"def",
"canary",
"return",
"Nil",
".",
"instance",
"unless",
"load?",
"addr",
"=",
"@info",
".",
"auxv",
"[",
":random",
"]",
"Helper",
".",
"unpack",
"(",
"bits",
"/",
"8",
",",
"@dumper",
".",
"dump",
"(",
"addr",
",",
"bits",
"/",
"8",
")",
")",
"&",
"0xffffffffffffff00",
"end"
] | Get the value of stack guard.
@return [Integer]
@example
h.canary
#=> 11342701118118205184 # 0x9d695e921adc9700 | [
"Get",
"the",
"value",
"of",
"stack",
"guard",
"."
] | 0608067e2d7601249cf01e725f7b8389e390d3f6 | https://github.com/david942j/heapinfo/blob/0608067e2d7601249cf01e725f7b8389e390d3f6/lib/heapinfo/process.rb#L284-L289 | train |
infertux/bashcov | lib/bashcov/xtrace.rb | Bashcov.Xtrace.read | def read
@field_stream.read = @read
field_count = FIELDS.length
fields = @field_stream.each(
self.class.delimiter, field_count, PS4_START_REGEXP
)
# +take(field_count)+ would be more natural here, but doesn't seem to
# play nicely with +Enumerator+s backed by +IO+ objects.
loop do
break if (hit = (1..field_count).map { fields.next }).empty?
parse_hit!(*hit)
end
@read.close unless @read.closed?
@files
end | ruby | def read
@field_stream.read = @read
field_count = FIELDS.length
fields = @field_stream.each(
self.class.delimiter, field_count, PS4_START_REGEXP
)
# +take(field_count)+ would be more natural here, but doesn't seem to
# play nicely with +Enumerator+s backed by +IO+ objects.
loop do
break if (hit = (1..field_count).map { fields.next }).empty?
parse_hit!(*hit)
end
@read.close unless @read.closed?
@files
end | [
"def",
"read",
"@field_stream",
".",
"read",
"=",
"@read",
"field_count",
"=",
"FIELDS",
".",
"length",
"fields",
"=",
"@field_stream",
".",
"each",
"(",
"self",
".",
"class",
".",
"delimiter",
",",
"field_count",
",",
"PS4_START_REGEXP",
")",
"# +take(field_count)+ would be more natural here, but doesn't seem to",
"# play nicely with +Enumerator+s backed by +IO+ objects.",
"loop",
"do",
"break",
"if",
"(",
"hit",
"=",
"(",
"1",
"..",
"field_count",
")",
".",
"map",
"{",
"fields",
".",
"next",
"}",
")",
".",
"empty?",
"parse_hit!",
"(",
"hit",
")",
"end",
"@read",
".",
"close",
"unless",
"@read",
".",
"closed?",
"@files",
"end"
] | Read fields extracted from Bash's debugging output
@return [Hash<Pathname, Array<Integer, nil>>] A hash mapping Bash scripts
to Simplecov-style coverage stats | [
"Read",
"fields",
"extracted",
"from",
"Bash",
"s",
"debugging",
"output"
] | 40730ae72b286e7508937e187fc000715d8a6892 | https://github.com/infertux/bashcov/blob/40730ae72b286e7508937e187fc000715d8a6892/lib/bashcov/xtrace.rb#L84-L103 | train |
infertux/bashcov | lib/bashcov/xtrace.rb | Bashcov.Xtrace.update_wd_stacks! | def update_wd_stacks!(pwd, oldpwd)
@pwd_stack[0] ||= pwd
@oldpwd_stack[0] ||= oldpwd unless oldpwd.to_s.empty?
# We haven't changed working directories; short-circuit.
return if pwd == @pwd_stack[-1]
# If the current +pwd+ is identical to the top of the +@oldpwd_stack+ and
# the current +oldpwd+ is identical to the second-to-top entry, then a
# previous cd/pushd has been undone.
if pwd == @oldpwd_stack[-1] && oldpwd == @oldpwd_stack[-2]
@pwd_stack.pop
@oldpwd_stack.pop
else # New cd/pushd
@pwd_stack << pwd
@oldpwd_stack << oldpwd
end
end | ruby | def update_wd_stacks!(pwd, oldpwd)
@pwd_stack[0] ||= pwd
@oldpwd_stack[0] ||= oldpwd unless oldpwd.to_s.empty?
# We haven't changed working directories; short-circuit.
return if pwd == @pwd_stack[-1]
# If the current +pwd+ is identical to the top of the +@oldpwd_stack+ and
# the current +oldpwd+ is identical to the second-to-top entry, then a
# previous cd/pushd has been undone.
if pwd == @oldpwd_stack[-1] && oldpwd == @oldpwd_stack[-2]
@pwd_stack.pop
@oldpwd_stack.pop
else # New cd/pushd
@pwd_stack << pwd
@oldpwd_stack << oldpwd
end
end | [
"def",
"update_wd_stacks!",
"(",
"pwd",
",",
"oldpwd",
")",
"@pwd_stack",
"[",
"0",
"]",
"||=",
"pwd",
"@oldpwd_stack",
"[",
"0",
"]",
"||=",
"oldpwd",
"unless",
"oldpwd",
".",
"to_s",
".",
"empty?",
"# We haven't changed working directories; short-circuit.",
"return",
"if",
"pwd",
"==",
"@pwd_stack",
"[",
"-",
"1",
"]",
"# If the current +pwd+ is identical to the top of the +@oldpwd_stack+ and",
"# the current +oldpwd+ is identical to the second-to-top entry, then a",
"# previous cd/pushd has been undone.",
"if",
"pwd",
"==",
"@oldpwd_stack",
"[",
"-",
"1",
"]",
"&&",
"oldpwd",
"==",
"@oldpwd_stack",
"[",
"-",
"2",
"]",
"@pwd_stack",
".",
"pop",
"@oldpwd_stack",
".",
"pop",
"else",
"# New cd/pushd",
"@pwd_stack",
"<<",
"pwd",
"@oldpwd_stack",
"<<",
"oldpwd",
"end",
"end"
] | Updates the stacks that track the history of values for +PWD+ and
+OLDPWD+
@param [Pathname] pwd expanded +PWD+
@param [Pathname] oldpwd expanded +OLDPWD+
@return [void] | [
"Updates",
"the",
"stacks",
"that",
"track",
"the",
"history",
"of",
"values",
"for",
"+",
"PWD",
"+",
"and",
"+",
"OLDPWD",
"+"
] | 40730ae72b286e7508937e187fc000715d8a6892 | https://github.com/infertux/bashcov/blob/40730ae72b286e7508937e187fc000715d8a6892/lib/bashcov/xtrace.rb#L169-L186 | train |
infertux/bashcov | lib/bashcov/detective.rb | Bashcov.Detective.shellscript? | def shellscript?(filename)
return false unless File.exist?(filename) && File.readable?(filename) \
&& File.file?(File.realpath(filename))
shellscript_shebang?(filename) || \
(shellscript_extension?(filename) && shellscript_syntax?(filename))
end | ruby | def shellscript?(filename)
return false unless File.exist?(filename) && File.readable?(filename) \
&& File.file?(File.realpath(filename))
shellscript_shebang?(filename) || \
(shellscript_extension?(filename) && shellscript_syntax?(filename))
end | [
"def",
"shellscript?",
"(",
"filename",
")",
"return",
"false",
"unless",
"File",
".",
"exist?",
"(",
"filename",
")",
"&&",
"File",
".",
"readable?",
"(",
"filename",
")",
"&&",
"File",
".",
"file?",
"(",
"File",
".",
"realpath",
"(",
"filename",
")",
")",
"shellscript_shebang?",
"(",
"filename",
")",
"||",
"(",
"shellscript_extension?",
"(",
"filename",
")",
"&&",
"shellscript_syntax?",
"(",
"filename",
")",
")",
"end"
] | Create an object that can be used for inferring whether a file is or is
not a shell script.
@param [String] bash_path path to a Bash interpreter
Checks whether the provided file refers to a shell script by
determining whether the first line is a shebang that refers to a shell
executable, or whether the file has a shellscript extension and contains
valid shell syntax.
@param [String,Pathname] filename the name of the file to be checked
@return [Boolean] whether +filename+ refers to a shell script
@note returns +false+ when +filename+ is not readable, even if +filename+
indeed refers to a shell script. | [
"Create",
"an",
"object",
"that",
"can",
"be",
"used",
"for",
"inferring",
"whether",
"a",
"file",
"is",
"or",
"is",
"not",
"a",
"shell",
"script",
"."
] | 40730ae72b286e7508937e187fc000715d8a6892 | https://github.com/infertux/bashcov/blob/40730ae72b286e7508937e187fc000715d8a6892/lib/bashcov/detective.rb#L33-L39 | train |
infertux/bashcov | lib/bashcov/field_stream.rb | Bashcov.FieldStream.each | def each(delimiter, field_count, start_match)
return enum_for(__method__, delimiter, field_count, start_match) unless block_given?
chunked = each_field(delimiter).chunk(&chunk_matches(start_match))
yield_fields = lambda do |(_, chunk)|
chunk.each { |e| yield e }
(field_count - chunk.size).times { yield "" }
end
# Skip junk that might appear before the first start-of-fields match
begin
n, chunk = chunked.next
yield_fields.call([n, chunk]) unless n.zero?
rescue StopIteration
return
end
chunked.each(&yield_fields)
end | ruby | def each(delimiter, field_count, start_match)
return enum_for(__method__, delimiter, field_count, start_match) unless block_given?
chunked = each_field(delimiter).chunk(&chunk_matches(start_match))
yield_fields = lambda do |(_, chunk)|
chunk.each { |e| yield e }
(field_count - chunk.size).times { yield "" }
end
# Skip junk that might appear before the first start-of-fields match
begin
n, chunk = chunked.next
yield_fields.call([n, chunk]) unless n.zero?
rescue StopIteration
return
end
chunked.each(&yield_fields)
end | [
"def",
"each",
"(",
"delimiter",
",",
"field_count",
",",
"start_match",
")",
"return",
"enum_for",
"(",
"__method__",
",",
"delimiter",
",",
"field_count",
",",
"start_match",
")",
"unless",
"block_given?",
"chunked",
"=",
"each_field",
"(",
"delimiter",
")",
".",
"chunk",
"(",
"chunk_matches",
"(",
"start_match",
")",
")",
"yield_fields",
"=",
"lambda",
"do",
"|",
"(",
"_",
",",
"chunk",
")",
"|",
"chunk",
".",
"each",
"{",
"|",
"e",
"|",
"yield",
"e",
"}",
"(",
"field_count",
"-",
"chunk",
".",
"size",
")",
".",
"times",
"{",
"yield",
"\"\"",
"}",
"end",
"# Skip junk that might appear before the first start-of-fields match",
"begin",
"n",
",",
"chunk",
"=",
"chunked",
".",
"next",
"yield_fields",
".",
"call",
"(",
"[",
"n",
",",
"chunk",
"]",
")",
"unless",
"n",
".",
"zero?",
"rescue",
"StopIteration",
"return",
"end",
"chunked",
".",
"each",
"(",
"yield_fields",
")",
"end"
] | Yields fields extracted from a input stream
@param [String, nil] delimiter the field separator
@param [Integer] field_count the number of fields to extract
@param [Regexp] start_match a +Regexp+ that, when matched against the
input stream, signifies the beginning of the next series of fields to
yield
@yieldparam [String] field each field extracted from the stream. If
+start_match+ is matched with fewer than +field_count+ fields yielded
since the last match, yields empty strings until +field_count+ is
reached. | [
"Yields",
"fields",
"extracted",
"from",
"a",
"input",
"stream"
] | 40730ae72b286e7508937e187fc000715d8a6892 | https://github.com/infertux/bashcov/blob/40730ae72b286e7508937e187fc000715d8a6892/lib/bashcov/field_stream.rb#L36-L55 | train |
malept/thermite | lib/thermite/package.rb | Thermite.Package.build_package | def build_package
filename = config.tarball_filename(config.toml[:package][:version])
relative_library_path = config.ruby_extension_path.sub("#{config.ruby_toplevel_dir}/", '')
prepare_built_library
Zlib::GzipWriter.open(filename) do |tgz|
Dir.chdir(config.ruby_toplevel_dir) do
Archive::Tar::Minitar.pack(relative_library_path, tgz)
end
end
end | ruby | def build_package
filename = config.tarball_filename(config.toml[:package][:version])
relative_library_path = config.ruby_extension_path.sub("#{config.ruby_toplevel_dir}/", '')
prepare_built_library
Zlib::GzipWriter.open(filename) do |tgz|
Dir.chdir(config.ruby_toplevel_dir) do
Archive::Tar::Minitar.pack(relative_library_path, tgz)
end
end
end | [
"def",
"build_package",
"filename",
"=",
"config",
".",
"tarball_filename",
"(",
"config",
".",
"toml",
"[",
":package",
"]",
"[",
":version",
"]",
")",
"relative_library_path",
"=",
"config",
".",
"ruby_extension_path",
".",
"sub",
"(",
"\"#{config.ruby_toplevel_dir}/\"",
",",
"''",
")",
"prepare_built_library",
"Zlib",
"::",
"GzipWriter",
".",
"open",
"(",
"filename",
")",
"do",
"|",
"tgz",
"|",
"Dir",
".",
"chdir",
"(",
"config",
".",
"ruby_toplevel_dir",
")",
"do",
"Archive",
"::",
"Tar",
"::",
"Minitar",
".",
"pack",
"(",
"relative_library_path",
",",
"tgz",
")",
"end",
"end",
"end"
] | Builds a tarball of the Rust-compiled shared library. | [
"Builds",
"a",
"tarball",
"of",
"the",
"Rust",
"-",
"compiled",
"shared",
"library",
"."
] | 9b380eb9e069909ff346fb3079d5be340deccaac | https://github.com/malept/thermite/blob/9b380eb9e069909ff346fb3079d5be340deccaac/lib/thermite/package.rb#L32-L41 | train |
malept/thermite | lib/thermite/util.rb | Thermite.Util.debug | def debug(msg)
# Should probably replace with a Logger
return unless config.debug_filename
@debug ||= File.open(config.debug_filename, 'w')
@debug.write("#{msg}\n")
@debug.flush
end | ruby | def debug(msg)
# Should probably replace with a Logger
return unless config.debug_filename
@debug ||= File.open(config.debug_filename, 'w')
@debug.write("#{msg}\n")
@debug.flush
end | [
"def",
"debug",
"(",
"msg",
")",
"# Should probably replace with a Logger",
"return",
"unless",
"config",
".",
"debug_filename",
"@debug",
"||=",
"File",
".",
"open",
"(",
"config",
".",
"debug_filename",
",",
"'w'",
")",
"@debug",
".",
"write",
"(",
"\"#{msg}\\n\"",
")",
"@debug",
".",
"flush",
"end"
] | Logs a debug message to the specified `config.debug_filename`, if set. | [
"Logs",
"a",
"debug",
"message",
"to",
"the",
"specified",
"config",
".",
"debug_filename",
"if",
"set",
"."
] | 9b380eb9e069909ff346fb3079d5be340deccaac | https://github.com/malept/thermite/blob/9b380eb9e069909ff346fb3079d5be340deccaac/lib/thermite/util.rb#L30-L37 | train |
malept/thermite | lib/thermite/custom_binary.rb | Thermite.CustomBinary.download_binary_from_custom_uri | def download_binary_from_custom_uri
return false unless config.binary_uri_format
version = config.crate_version
uri ||= format(
config.binary_uri_format,
filename: config.tarball_filename(version),
version: version
)
return false unless (tgz = download_versioned_binary(uri, version))
debug "Unpacking binary from Cargo version: #{File.basename(uri)}"
unpack_tarball(tgz)
prepare_downloaded_library
true
end | ruby | def download_binary_from_custom_uri
return false unless config.binary_uri_format
version = config.crate_version
uri ||= format(
config.binary_uri_format,
filename: config.tarball_filename(version),
version: version
)
return false unless (tgz = download_versioned_binary(uri, version))
debug "Unpacking binary from Cargo version: #{File.basename(uri)}"
unpack_tarball(tgz)
prepare_downloaded_library
true
end | [
"def",
"download_binary_from_custom_uri",
"return",
"false",
"unless",
"config",
".",
"binary_uri_format",
"version",
"=",
"config",
".",
"crate_version",
"uri",
"||=",
"format",
"(",
"config",
".",
"binary_uri_format",
",",
"filename",
":",
"config",
".",
"tarball_filename",
"(",
"version",
")",
",",
"version",
":",
"version",
")",
"return",
"false",
"unless",
"(",
"tgz",
"=",
"download_versioned_binary",
"(",
"uri",
",",
"version",
")",
")",
"debug",
"\"Unpacking binary from Cargo version: #{File.basename(uri)}\"",
"unpack_tarball",
"(",
"tgz",
")",
"prepare_downloaded_library",
"true",
"end"
] | Downloads a Rust binary using a custom URI format, given the target OS and architecture.
Requires the `binary_uri_format` option to be set. The version of the binary is determined by
the crate version given in `Cargo.toml`.
Returns whether a binary was found and unpacked. | [
"Downloads",
"a",
"Rust",
"binary",
"using",
"a",
"custom",
"URI",
"format",
"given",
"the",
"target",
"OS",
"and",
"architecture",
"."
] | 9b380eb9e069909ff346fb3079d5be340deccaac | https://github.com/malept/thermite/blob/9b380eb9e069909ff346fb3079d5be340deccaac/lib/thermite/custom_binary.rb#L36-L52 | train |
piotrmurach/github_cli | lib/github_cli/dsl.rb | GithubCLI.DSL.on_error | def on_error
yield
rescue Github::Error::NotFound => e
terminal.newline
ui.error 'Resource Not Found'
terminal.newline
exit 15
rescue GithubCLI::GithubCLIError => e
GithubCLI.ui.error e.message
GithubCLI.ui.debug e
exit e.status_code
rescue Interrupt => e
GithubCLI.ui.error "\nQuitting..."
GithubCLI.ui.debug e
exit 1
rescue SystemExit => e
exit e.status
rescue Exception => e
GithubCLI.ui.error "\nFatal error has occurred. " + e.message.to_s
GithubCLI.ui.debug e
exit 1
end | ruby | def on_error
yield
rescue Github::Error::NotFound => e
terminal.newline
ui.error 'Resource Not Found'
terminal.newline
exit 15
rescue GithubCLI::GithubCLIError => e
GithubCLI.ui.error e.message
GithubCLI.ui.debug e
exit e.status_code
rescue Interrupt => e
GithubCLI.ui.error "\nQuitting..."
GithubCLI.ui.debug e
exit 1
rescue SystemExit => e
exit e.status
rescue Exception => e
GithubCLI.ui.error "\nFatal error has occurred. " + e.message.to_s
GithubCLI.ui.debug e
exit 1
end | [
"def",
"on_error",
"yield",
"rescue",
"Github",
"::",
"Error",
"::",
"NotFound",
"=>",
"e",
"terminal",
".",
"newline",
"ui",
".",
"error",
"'Resource Not Found'",
"terminal",
".",
"newline",
"exit",
"15",
"rescue",
"GithubCLI",
"::",
"GithubCLIError",
"=>",
"e",
"GithubCLI",
".",
"ui",
".",
"error",
"e",
".",
"message",
"GithubCLI",
".",
"ui",
".",
"debug",
"e",
"exit",
"e",
".",
"status_code",
"rescue",
"Interrupt",
"=>",
"e",
"GithubCLI",
".",
"ui",
".",
"error",
"\"\\nQuitting...\"",
"GithubCLI",
".",
"ui",
".",
"debug",
"e",
"exit",
"1",
"rescue",
"SystemExit",
"=>",
"e",
"exit",
"e",
".",
"status",
"rescue",
"Exception",
"=>",
"e",
"GithubCLI",
".",
"ui",
".",
"error",
"\"\\nFatal error has occurred. \"",
"+",
"e",
".",
"message",
".",
"to_s",
"GithubCLI",
".",
"ui",
".",
"debug",
"e",
"exit",
"1",
"end"
] | Defines behaviour on error to emit consistent type. | [
"Defines",
"behaviour",
"on",
"error",
"to",
"emit",
"consistent",
"type",
"."
] | 394845fb629351917beeb62e607b833420410930 | https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/dsl.rb#L18-L39 | train |
piotrmurach/github_cli | lib/github_cli/util.rb | GithubCLI.Util.convert_value | def convert_value(value)
case value
when true then "true"
when false then "false"
when Hash then convert_value(value.values)
when Array then value.map(&:to_s)
else value.to_s
end
end | ruby | def convert_value(value)
case value
when true then "true"
when false then "false"
when Hash then convert_value(value.values)
when Array then value.map(&:to_s)
else value.to_s
end
end | [
"def",
"convert_value",
"(",
"value",
")",
"case",
"value",
"when",
"true",
"then",
"\"true\"",
"when",
"false",
"then",
"\"false\"",
"when",
"Hash",
"then",
"convert_value",
"(",
"value",
".",
"values",
")",
"when",
"Array",
"then",
"value",
".",
"map",
"(",
":to_s",
")",
"else",
"value",
".",
"to_s",
"end",
"end"
] | Attempts to convert value object to string | [
"Attempts",
"to",
"convert",
"value",
"object",
"to",
"string"
] | 394845fb629351917beeb62e607b833420410930 | https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/util.rb#L37-L45 | train |
piotrmurach/github_cli | lib/github_cli/manpage.rb | GithubCLI.Manpage.man_dir | def man_dir(path = nil)
if @man_dir.nil? || path
man_path = path || File.expand_path('../man', __FILE__)
if File.directory?(man_path)
@man_dir = man_path
else
fail "Manuals directory `#{man_path}` does not exist"
end
end
@man_dir
end | ruby | def man_dir(path = nil)
if @man_dir.nil? || path
man_path = path || File.expand_path('../man', __FILE__)
if File.directory?(man_path)
@man_dir = man_path
else
fail "Manuals directory `#{man_path}` does not exist"
end
end
@man_dir
end | [
"def",
"man_dir",
"(",
"path",
"=",
"nil",
")",
"if",
"@man_dir",
".",
"nil?",
"||",
"path",
"man_path",
"=",
"path",
"||",
"File",
".",
"expand_path",
"(",
"'../man'",
",",
"__FILE__",
")",
"if",
"File",
".",
"directory?",
"(",
"man_path",
")",
"@man_dir",
"=",
"man_path",
"else",
"fail",
"\"Manuals directory `#{man_path}` does not exist\"",
"end",
"end",
"@man_dir",
"end"
] | Full path to manual directory
@return [String]
@api private | [
"Full",
"path",
"to",
"manual",
"directory"
] | 394845fb629351917beeb62e607b833420410930 | https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/manpage.rb#L20-L31 | train |
piotrmurach/github_cli | lib/github_cli/manpage.rb | GithubCLI.Manpage.manpage? | def manpage?(name, section = nil)
return false if name.nil?
manpages(name, section).any?
end | ruby | def manpage?(name, section = nil)
return false if name.nil?
manpages(name, section).any?
end | [
"def",
"manpage?",
"(",
"name",
",",
"section",
"=",
"nil",
")",
"return",
"false",
"if",
"name",
".",
"nil?",
"manpages",
"(",
"name",
",",
"section",
")",
".",
"any?",
"end"
] | Check if manual exists for a command
@param [String] command
the command name
@api public | [
"Check",
"if",
"manual",
"exists",
"for",
"a",
"command"
] | 394845fb629351917beeb62e607b833420410930 | https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/manpage.rb#L48-L52 | train |
piotrmurach/github_cli | lib/github_cli/manpage.rb | GithubCLI.Manpage.read | def read(name, section = nil)
return if name.nil?
paths = manpages(name)
return if paths.empty?
if paths.size == 1
manpath = paths[0]
elsif paths.size > 1
prompt = TTY::Prompt.new
manpath = prompt.select("Choose manual to view?", paths)
end
if manpath
run(manpath)
else
abort("No manuals found for #{name}")
end
end | ruby | def read(name, section = nil)
return if name.nil?
paths = manpages(name)
return if paths.empty?
if paths.size == 1
manpath = paths[0]
elsif paths.size > 1
prompt = TTY::Prompt.new
manpath = prompt.select("Choose manual to view?", paths)
end
if manpath
run(manpath)
else
abort("No manuals found for #{name}")
end
end | [
"def",
"read",
"(",
"name",
",",
"section",
"=",
"nil",
")",
"return",
"if",
"name",
".",
"nil?",
"paths",
"=",
"manpages",
"(",
"name",
")",
"return",
"if",
"paths",
".",
"empty?",
"if",
"paths",
".",
"size",
"==",
"1",
"manpath",
"=",
"paths",
"[",
"0",
"]",
"elsif",
"paths",
".",
"size",
">",
"1",
"prompt",
"=",
"TTY",
"::",
"Prompt",
".",
"new",
"manpath",
"=",
"prompt",
".",
"select",
"(",
"\"Choose manual to view?\"",
",",
"paths",
")",
"end",
"if",
"manpath",
"run",
"(",
"manpath",
")",
"else",
"abort",
"(",
"\"No manuals found for #{name}\"",
")",
"end",
"end"
] | Read manual page
@api public | [
"Read",
"manual",
"page"
] | 394845fb629351917beeb62e607b833420410930 | https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/manpage.rb#L76-L93 | train |
piotrmurach/github_cli | lib/github_cli/pager.rb | GithubCLI.Pager.page | def page
return if not $stdout.tty?
read_io, write_io = IO.pipe
if Kernel.fork
$stdin.reopen(read_io)
read_io.close
write_io.close
# Don't page if the input is short enough
ENV['LESS'] = 'FSRX'
# Wait until we have input before we start the pager
Kernel.select [$stdin]
pager = Pager.pager_command
Kernel.exec pager rescue Kernel.exec "/bin/sh", "-c", pager
else
# Child process
$stdout.reopen(write_io)
$stderr.reopen(write_io) if $stderr.tty?
write_io.close
read_io.close
end
end | ruby | def page
return if not $stdout.tty?
read_io, write_io = IO.pipe
if Kernel.fork
$stdin.reopen(read_io)
read_io.close
write_io.close
# Don't page if the input is short enough
ENV['LESS'] = 'FSRX'
# Wait until we have input before we start the pager
Kernel.select [$stdin]
pager = Pager.pager_command
Kernel.exec pager rescue Kernel.exec "/bin/sh", "-c", pager
else
# Child process
$stdout.reopen(write_io)
$stderr.reopen(write_io) if $stderr.tty?
write_io.close
read_io.close
end
end | [
"def",
"page",
"return",
"if",
"not",
"$stdout",
".",
"tty?",
"read_io",
",",
"write_io",
"=",
"IO",
".",
"pipe",
"if",
"Kernel",
".",
"fork",
"$stdin",
".",
"reopen",
"(",
"read_io",
")",
"read_io",
".",
"close",
"write_io",
".",
"close",
"# Don't page if the input is short enough",
"ENV",
"[",
"'LESS'",
"]",
"=",
"'FSRX'",
"# Wait until we have input before we start the pager",
"Kernel",
".",
"select",
"[",
"$stdin",
"]",
"pager",
"=",
"Pager",
".",
"pager_command",
"Kernel",
".",
"exec",
"pager",
"rescue",
"Kernel",
".",
"exec",
"\"/bin/sh\"",
",",
"\"-c\"",
",",
"pager",
"else",
"# Child process",
"$stdout",
".",
"reopen",
"(",
"write_io",
")",
"$stderr",
".",
"reopen",
"(",
"write_io",
")",
"if",
"$stderr",
".",
"tty?",
"write_io",
".",
"close",
"read_io",
".",
"close",
"end",
"end"
] | Pages output using configured pager. | [
"Pages",
"output",
"using",
"configured",
"pager",
"."
] | 394845fb629351917beeb62e607b833420410930 | https://github.com/piotrmurach/github_cli/blob/394845fb629351917beeb62e607b833420410930/lib/github_cli/pager.rb#L40-L66 | train |
Sutto/rocket_pants | lib/rocket_pants/controller/rescuable.rb | RocketPants.Rescuable.process_action | def process_action(*args)
super
rescue Exception => exception
raise if RocketPants.pass_through_errors?
# Otherwise, use the default built in handler.
logger.error "Exception occured: #{exception.class.name} - #{exception.message}"
logger.error "Exception backtrace:"
exception.backtrace[0, 10].each do |backtrace_line|
logger.error "=> #{backtrace_line}"
end
exception_notifier_callback.call(self, exception, request)
render_error exception
end | ruby | def process_action(*args)
super
rescue Exception => exception
raise if RocketPants.pass_through_errors?
# Otherwise, use the default built in handler.
logger.error "Exception occured: #{exception.class.name} - #{exception.message}"
logger.error "Exception backtrace:"
exception.backtrace[0, 10].each do |backtrace_line|
logger.error "=> #{backtrace_line}"
end
exception_notifier_callback.call(self, exception, request)
render_error exception
end | [
"def",
"process_action",
"(",
"*",
"args",
")",
"super",
"rescue",
"Exception",
"=>",
"exception",
"raise",
"if",
"RocketPants",
".",
"pass_through_errors?",
"# Otherwise, use the default built in handler.",
"logger",
".",
"error",
"\"Exception occured: #{exception.class.name} - #{exception.message}\"",
"logger",
".",
"error",
"\"Exception backtrace:\"",
"exception",
".",
"backtrace",
"[",
"0",
",",
"10",
"]",
".",
"each",
"do",
"|",
"backtrace_line",
"|",
"logger",
".",
"error",
"\"=> #{backtrace_line}\"",
"end",
"exception_notifier_callback",
".",
"call",
"(",
"self",
",",
"exception",
",",
"request",
")",
"render_error",
"exception",
"end"
] | Overrides the processing internals to rescue any exceptions and handle them with the
registered exception rescue handler. | [
"Overrides",
"the",
"processing",
"internals",
"to",
"rescue",
"any",
"exceptions",
"and",
"handle",
"them",
"with",
"the",
"registered",
"exception",
"rescue",
"handler",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/rescuable.rb#L60-L72 | train |
Sutto/rocket_pants | lib/rocket_pants/controller/error_handling.rb | RocketPants.ErrorHandling.error! | def error!(name, *args)
context = args.extract_options!
klass = Errors[name] || Error
exception = klass.new(*args).tap { |e| e.context = context }
raise exception
end | ruby | def error!(name, *args)
context = args.extract_options!
klass = Errors[name] || Error
exception = klass.new(*args).tap { |e| e.context = context }
raise exception
end | [
"def",
"error!",
"(",
"name",
",",
"*",
"args",
")",
"context",
"=",
"args",
".",
"extract_options!",
"klass",
"=",
"Errors",
"[",
"name",
"]",
"||",
"Error",
"exception",
"=",
"klass",
".",
"new",
"(",
"args",
")",
".",
"tap",
"{",
"|",
"e",
"|",
"e",
".",
"context",
"=",
"context",
"}",
"raise",
"exception",
"end"
] | Dynamically looks up and then throws the error given by a symbolic name.
Optionally takes a string message argument and a hash of 'context'.
@overload error!(name, context = {})
@param [Symbol] name the name of the exception, looked up using RocketPants::Errors
@param [Hash{Symbol => Object}] context the options passed to the error message translation.
@overload error!(name, message, context = {})
@param [Symbol] name the name of the exception, looked up using RocketPants::Errors
@param [String] message an optional message describing the error
@param [Hash{Symbol => Object}] context the options passed to the error message translation.
@raise [RocketPants::Error] the error from the given options | [
"Dynamically",
"looks",
"up",
"and",
"then",
"throws",
"the",
"error",
"given",
"by",
"a",
"symbolic",
"name",
".",
"Optionally",
"takes",
"a",
"string",
"message",
"argument",
"and",
"a",
"hash",
"of",
"context",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/error_handling.rb#L40-L45 | train |
Sutto/rocket_pants | lib/rocket_pants/controller/error_handling.rb | RocketPants.ErrorHandling.lookup_error_metadata | def lookup_error_metadata(exception)
context = lookup_error_context exception
context.fetch(:metadata, {}).merge lookup_error_extras(exception)
end | ruby | def lookup_error_metadata(exception)
context = lookup_error_context exception
context.fetch(:metadata, {}).merge lookup_error_extras(exception)
end | [
"def",
"lookup_error_metadata",
"(",
"exception",
")",
"context",
"=",
"lookup_error_context",
"exception",
"context",
".",
"fetch",
"(",
":metadata",
",",
"{",
"}",
")",
".",
"merge",
"lookup_error_extras",
"(",
"exception",
")",
"end"
] | Returns extra error details for a given object, making it useable
for hooking in external exceptions. | [
"Returns",
"extra",
"error",
"details",
"for",
"a",
"given",
"object",
"making",
"it",
"useable",
"for",
"hooking",
"in",
"external",
"exceptions",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/error_handling.rb#L102-L105 | train |
Sutto/rocket_pants | lib/rocket_pants/controller/error_handling.rb | RocketPants.ErrorHandling.render_error | def render_error(exception)
logger.debug "Exception raised: #{exception.class.name}: #{exception.message}" if logger
# When a normalised class is present, make sure we
# convert it to a useable error class.
normalised_class = exception.class.ancestors.detect do |klass|
klass < StandardError and error_mapping.has_key?(klass)
end
if normalised_class
mapped = error_mapping[normalised_class]
if mapped.respond_to?(:call)
exception = mapped.call(exception)
else
exception = mapped.new exception.message
end
end
self.status = lookup_error_status(exception)
render_json({
:error => lookup_error_name(exception).to_s,
:error_description => lookup_error_message(exception)
}.merge(lookup_error_metadata(exception)))
end | ruby | def render_error(exception)
logger.debug "Exception raised: #{exception.class.name}: #{exception.message}" if logger
# When a normalised class is present, make sure we
# convert it to a useable error class.
normalised_class = exception.class.ancestors.detect do |klass|
klass < StandardError and error_mapping.has_key?(klass)
end
if normalised_class
mapped = error_mapping[normalised_class]
if mapped.respond_to?(:call)
exception = mapped.call(exception)
else
exception = mapped.new exception.message
end
end
self.status = lookup_error_status(exception)
render_json({
:error => lookup_error_name(exception).to_s,
:error_description => lookup_error_message(exception)
}.merge(lookup_error_metadata(exception)))
end | [
"def",
"render_error",
"(",
"exception",
")",
"logger",
".",
"debug",
"\"Exception raised: #{exception.class.name}: #{exception.message}\"",
"if",
"logger",
"# When a normalised class is present, make sure we",
"# convert it to a useable error class.",
"normalised_class",
"=",
"exception",
".",
"class",
".",
"ancestors",
".",
"detect",
"do",
"|",
"klass",
"|",
"klass",
"<",
"StandardError",
"and",
"error_mapping",
".",
"has_key?",
"(",
"klass",
")",
"end",
"if",
"normalised_class",
"mapped",
"=",
"error_mapping",
"[",
"normalised_class",
"]",
"if",
"mapped",
".",
"respond_to?",
"(",
":call",
")",
"exception",
"=",
"mapped",
".",
"call",
"(",
"exception",
")",
"else",
"exception",
"=",
"mapped",
".",
"new",
"exception",
".",
"message",
"end",
"end",
"self",
".",
"status",
"=",
"lookup_error_status",
"(",
"exception",
")",
"render_json",
"(",
"{",
":error",
"=>",
"lookup_error_name",
"(",
"exception",
")",
".",
"to_s",
",",
":error_description",
"=>",
"lookup_error_message",
"(",
"exception",
")",
"}",
".",
"merge",
"(",
"lookup_error_metadata",
"(",
"exception",
")",
")",
")",
"end"
] | Renders an exception as JSON using a nicer version of the error name and
error message, following the typically error standard as laid out in the JSON
api design.
@param [StandardError] exception the error to render a response for. | [
"Renders",
"an",
"exception",
"as",
"JSON",
"using",
"a",
"nicer",
"version",
"of",
"the",
"error",
"name",
"and",
"error",
"message",
"following",
"the",
"typically",
"error",
"standard",
"as",
"laid",
"out",
"in",
"the",
"JSON",
"api",
"design",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/error_handling.rb#L111-L131 | train |
Sutto/rocket_pants | lib/rocket_pants/client.rb | RocketPants.Client.transform_response | def transform_response(response, options = {})
# Now unpack the response into the data types.
inner = response.delete("response")
objects = unpack inner, options
# Unpack pagination as a special case.
if response.has_key?("pagination")
paginated_response objects, response
else
objects
end
end | ruby | def transform_response(response, options = {})
# Now unpack the response into the data types.
inner = response.delete("response")
objects = unpack inner, options
# Unpack pagination as a special case.
if response.has_key?("pagination")
paginated_response objects, response
else
objects
end
end | [
"def",
"transform_response",
"(",
"response",
",",
"options",
"=",
"{",
"}",
")",
"# Now unpack the response into the data types.",
"inner",
"=",
"response",
".",
"delete",
"(",
"\"response\"",
")",
"objects",
"=",
"unpack",
"inner",
",",
"options",
"# Unpack pagination as a special case.",
"if",
"response",
".",
"has_key?",
"(",
"\"pagination\"",
")",
"paginated_response",
"objects",
",",
"response",
"else",
"objects",
"end",
"end"
] | Give a response hash from the api, will transform it into
the correct data type.
@param [Hash] response the incoming response
@param [hash] options any options to pass through for transformation
@return [Object] the transformed response. | [
"Give",
"a",
"response",
"hash",
"from",
"the",
"api",
"will",
"transform",
"it",
"into",
"the",
"correct",
"data",
"type",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/client.rb#L83-L93 | train |
Sutto/rocket_pants | lib/rocket_pants/client.rb | RocketPants.Client.paginated_response | def paginated_response(objects, container)
pagination = container.delete("pagination")
WillPaginate::Collection.create(pagination["current"], pagination["per_page"]) do |collection|
collection.replace objects
collection.total_entries = pagination["count"]
end
end | ruby | def paginated_response(objects, container)
pagination = container.delete("pagination")
WillPaginate::Collection.create(pagination["current"], pagination["per_page"]) do |collection|
collection.replace objects
collection.total_entries = pagination["count"]
end
end | [
"def",
"paginated_response",
"(",
"objects",
",",
"container",
")",
"pagination",
"=",
"container",
".",
"delete",
"(",
"\"pagination\"",
")",
"WillPaginate",
"::",
"Collection",
".",
"create",
"(",
"pagination",
"[",
"\"current\"",
"]",
",",
"pagination",
"[",
"\"per_page\"",
"]",
")",
"do",
"|",
"collection",
"|",
"collection",
".",
"replace",
"objects",
"collection",
".",
"total_entries",
"=",
"pagination",
"[",
"\"count\"",
"]",
"end",
"end"
] | Returns an API response wrapped in a will_paginate collection
using the pagination key in the response container to set up
the current number of total entries and page details.
@param [Array<Object>] objects the actual response contents
@param [Hash{String => Object}] The response container
@option container [Hash] "pagination" the pagination data to use. | [
"Returns",
"an",
"API",
"response",
"wrapped",
"in",
"a",
"will_paginate",
"collection",
"using",
"the",
"pagination",
"key",
"in",
"the",
"response",
"container",
"to",
"set",
"up",
"the",
"current",
"number",
"of",
"total",
"entries",
"and",
"page",
"details",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/client.rb#L101-L107 | train |
Sutto/rocket_pants | lib/rocket_pants/client.rb | RocketPants.Client.unpack | def unpack(object, options = {})
transformer = options[:transformer] || options[:as]
transformer ? transformer.call(object) : object
end | ruby | def unpack(object, options = {})
transformer = options[:transformer] || options[:as]
transformer ? transformer.call(object) : object
end | [
"def",
"unpack",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"transformer",
"=",
"options",
"[",
":transformer",
"]",
"||",
"options",
"[",
":as",
"]",
"transformer",
"?",
"transformer",
".",
"call",
"(",
"object",
")",
":",
"object",
"end"
] | Finds and uses the transformer for a given incoming object to
unpack it into a useful data type.
@param [Hash, Array<Hash>] object the response object to unpack
@param [Hash] options the unpacking options
@option options [Hash] :transformer,:as the transformer to use
@return The transformed data or the data itself when no transformer is specified. | [
"Finds",
"and",
"uses",
"the",
"transformer",
"for",
"a",
"given",
"incoming",
"object",
"to",
"unpack",
"it",
"into",
"a",
"useful",
"data",
"type",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/client.rb#L115-L118 | train |
Sutto/rocket_pants | lib/rocket_pants/controller/linking.rb | RocketPants.Linking.links | def links(links = {})
links.each_pair do |rel, uri|
link rel, uri if uri
end
end | ruby | def links(links = {})
links.each_pair do |rel, uri|
link rel, uri if uri
end
end | [
"def",
"links",
"(",
"links",
"=",
"{",
"}",
")",
"links",
".",
"each_pair",
"do",
"|",
"rel",
",",
"uri",
"|",
"link",
"rel",
",",
"uri",
"if",
"uri",
"end",
"end"
] | Lets you add a series of links for the current resource.
@param [Hash{Symbol => String}] links a hash of links. Those with nil as the value are skipped. | [
"Lets",
"you",
"add",
"a",
"series",
"of",
"links",
"for",
"the",
"current",
"resource",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/linking.rb#L18-L22 | train |
Sutto/rocket_pants | lib/rocket_pants/controller/respondable.rb | RocketPants.Respondable.render_json | def render_json(json, options = {})
# Setup data from options
self.status = options[:status] if options[:status]
self.content_type = options[:content_type] if options[:content_type]
options = options.slice(*RENDERING_OPTIONS)
# Don't convert raw strings to JSON.
json = encode_to_json(json) unless json.respond_to?(:to_str)
# Encode the object to json.
self.status ||= :ok
self.content_type ||= Mime::JSON
self.response_body = json
headers['Content-Length'] = Rack::Utils.bytesize(json).to_s
end | ruby | def render_json(json, options = {})
# Setup data from options
self.status = options[:status] if options[:status]
self.content_type = options[:content_type] if options[:content_type]
options = options.slice(*RENDERING_OPTIONS)
# Don't convert raw strings to JSON.
json = encode_to_json(json) unless json.respond_to?(:to_str)
# Encode the object to json.
self.status ||= :ok
self.content_type ||= Mime::JSON
self.response_body = json
headers['Content-Length'] = Rack::Utils.bytesize(json).to_s
end | [
"def",
"render_json",
"(",
"json",
",",
"options",
"=",
"{",
"}",
")",
"# Setup data from options",
"self",
".",
"status",
"=",
"options",
"[",
":status",
"]",
"if",
"options",
"[",
":status",
"]",
"self",
".",
"content_type",
"=",
"options",
"[",
":content_type",
"]",
"if",
"options",
"[",
":content_type",
"]",
"options",
"=",
"options",
".",
"slice",
"(",
"RENDERING_OPTIONS",
")",
"# Don't convert raw strings to JSON.",
"json",
"=",
"encode_to_json",
"(",
"json",
")",
"unless",
"json",
".",
"respond_to?",
"(",
":to_str",
")",
"# Encode the object to json.",
"self",
".",
"status",
"||=",
":ok",
"self",
".",
"content_type",
"||=",
"Mime",
"::",
"JSON",
"self",
".",
"response_body",
"=",
"json",
"headers",
"[",
"'Content-Length'",
"]",
"=",
"Rack",
"::",
"Utils",
".",
"bytesize",
"(",
"json",
")",
".",
"to_s",
"end"
] | Given a json object or encoded json, will encode it
and set it to be the output of the given page. | [
"Given",
"a",
"json",
"object",
"or",
"encoded",
"json",
"will",
"encode",
"it",
"and",
"set",
"it",
"to",
"be",
"the",
"output",
"of",
"the",
"given",
"page",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/respondable.rb#L117-L129 | train |
Sutto/rocket_pants | lib/rocket_pants/controller/respondable.rb | RocketPants.Respondable.exposes | def exposes(object, options = {})
if Respondable.paginated?(object)
paginated object, options
elsif Respondable.collection?(object)
collection object, options
else
if Respondable.invalid?(object)
error! :invalid_resource, object.errors
else
resource object, options
end
end
end | ruby | def exposes(object, options = {})
if Respondable.paginated?(object)
paginated object, options
elsif Respondable.collection?(object)
collection object, options
else
if Respondable.invalid?(object)
error! :invalid_resource, object.errors
else
resource object, options
end
end
end | [
"def",
"exposes",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"if",
"Respondable",
".",
"paginated?",
"(",
"object",
")",
"paginated",
"object",
",",
"options",
"elsif",
"Respondable",
".",
"collection?",
"(",
"object",
")",
"collection",
"object",
",",
"options",
"else",
"if",
"Respondable",
".",
"invalid?",
"(",
"object",
")",
"error!",
":invalid_resource",
",",
"object",
".",
"errors",
"else",
"resource",
"object",
",",
"options",
"end",
"end",
"end"
] | Exposes an object to the response - Essentiall, it tells the
controller that this is what we need to render. | [
"Exposes",
"an",
"object",
"to",
"the",
"response",
"-",
"Essentiall",
"it",
"tells",
"the",
"controller",
"that",
"this",
"is",
"what",
"we",
"need",
"to",
"render",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/respondable.rb#L163-L175 | train |
Sutto/rocket_pants | lib/rocket_pants/controller/respondable.rb | RocketPants.Respondable.metadata_for | def metadata_for(object, options, type, singular)
{}.tap do |metadata|
metadata[:count] = object.length unless singular
metadata[:pagination] = Respondable.extract_pagination(object) if type == :paginated
metadata.merge! options[:metadata] if options[:metadata]
end
end | ruby | def metadata_for(object, options, type, singular)
{}.tap do |metadata|
metadata[:count] = object.length unless singular
metadata[:pagination] = Respondable.extract_pagination(object) if type == :paginated
metadata.merge! options[:metadata] if options[:metadata]
end
end | [
"def",
"metadata_for",
"(",
"object",
",",
"options",
",",
"type",
",",
"singular",
")",
"{",
"}",
".",
"tap",
"do",
"|",
"metadata",
"|",
"metadata",
"[",
":count",
"]",
"=",
"object",
".",
"length",
"unless",
"singular",
"metadata",
"[",
":pagination",
"]",
"=",
"Respondable",
".",
"extract_pagination",
"(",
"object",
")",
"if",
"type",
"==",
":paginated",
"metadata",
".",
"merge!",
"options",
"[",
":metadata",
"]",
"if",
"options",
"[",
":metadata",
"]",
"end",
"end"
] | Extracts the metadata for the current response, merging in options etc.
Implements a simple hook to allow adding extra metadata to your api.
@param [Object] object the data being exposed
@param [Hash{Symbol => Object}] options expose options optionally including new metadata.
@param [Symbol] type the type of the current object
@param [true,false] singular true iff the current object is a singular resource | [
"Extracts",
"the",
"metadata",
"for",
"the",
"current",
"response",
"merging",
"in",
"options",
"etc",
".",
"Implements",
"a",
"simple",
"hook",
"to",
"allow",
"adding",
"extra",
"metadata",
"to",
"your",
"api",
"."
] | bddc27ada67a11ff34fa8065fe2b1b2627bd28ff | https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/respondable.rb#L221-L227 | train |
petems/tugboat | lib/tugboat/config.rb | Tugboat.Configuration.create_config_file | def create_config_file(access_token, ssh_key_path, ssh_user, ssh_port, region, image, size, ssh_key, private_networking, backups_enabled, ip6, timeout)
# Default SSH Key path
ssh_key_path = File.join('~', DEFAULT_SSH_KEY_PATH) if ssh_key_path.empty?
ssh_user = 'root' if ssh_user.empty?
ssh_port = DEFAULT_SSH_PORT if ssh_port.empty?
region = DEFAULT_REGION if region.empty?
image = DEFAULT_IMAGE if image.empty?
size = DEFAULT_SIZE if size.empty?
default_ssh_key = DEFAULT_SSH_KEY if ssh_key.empty?
if private_networking.empty?
private_networking = DEFAULT_PRIVATE_NETWORKING
end
backups_enabled = DEFAULT_BACKUPS_ENABLED if backups_enabled.empty?
ip6 = DEFAULT_IP6 if ip6.empty?
timeout = DEFAULT_TIMEOUT if timeout.empty?
require 'yaml'
File.open(@path, File::RDWR | File::TRUNC | File::CREAT, 0o600) do |file|
data = {
'authentication' => {
'access_token' => access_token
},
'connection' => {
'timeout' => timeout
},
'ssh' => {
'ssh_user' => ssh_user,
'ssh_key_path' => ssh_key_path,
'ssh_port' => ssh_port
},
'defaults' => {
'region' => region,
'image' => image,
'size' => size,
'ssh_key' => ssh_key,
'private_networking' => private_networking,
'backups_enabled' => backups_enabled,
'ip6' => ip6
}
}
file.write data.to_yaml
end
end | ruby | def create_config_file(access_token, ssh_key_path, ssh_user, ssh_port, region, image, size, ssh_key, private_networking, backups_enabled, ip6, timeout)
# Default SSH Key path
ssh_key_path = File.join('~', DEFAULT_SSH_KEY_PATH) if ssh_key_path.empty?
ssh_user = 'root' if ssh_user.empty?
ssh_port = DEFAULT_SSH_PORT if ssh_port.empty?
region = DEFAULT_REGION if region.empty?
image = DEFAULT_IMAGE if image.empty?
size = DEFAULT_SIZE if size.empty?
default_ssh_key = DEFAULT_SSH_KEY if ssh_key.empty?
if private_networking.empty?
private_networking = DEFAULT_PRIVATE_NETWORKING
end
backups_enabled = DEFAULT_BACKUPS_ENABLED if backups_enabled.empty?
ip6 = DEFAULT_IP6 if ip6.empty?
timeout = DEFAULT_TIMEOUT if timeout.empty?
require 'yaml'
File.open(@path, File::RDWR | File::TRUNC | File::CREAT, 0o600) do |file|
data = {
'authentication' => {
'access_token' => access_token
},
'connection' => {
'timeout' => timeout
},
'ssh' => {
'ssh_user' => ssh_user,
'ssh_key_path' => ssh_key_path,
'ssh_port' => ssh_port
},
'defaults' => {
'region' => region,
'image' => image,
'size' => size,
'ssh_key' => ssh_key,
'private_networking' => private_networking,
'backups_enabled' => backups_enabled,
'ip6' => ip6
}
}
file.write data.to_yaml
end
end | [
"def",
"create_config_file",
"(",
"access_token",
",",
"ssh_key_path",
",",
"ssh_user",
",",
"ssh_port",
",",
"region",
",",
"image",
",",
"size",
",",
"ssh_key",
",",
"private_networking",
",",
"backups_enabled",
",",
"ip6",
",",
"timeout",
")",
"# Default SSH Key path",
"ssh_key_path",
"=",
"File",
".",
"join",
"(",
"'~'",
",",
"DEFAULT_SSH_KEY_PATH",
")",
"if",
"ssh_key_path",
".",
"empty?",
"ssh_user",
"=",
"'root'",
"if",
"ssh_user",
".",
"empty?",
"ssh_port",
"=",
"DEFAULT_SSH_PORT",
"if",
"ssh_port",
".",
"empty?",
"region",
"=",
"DEFAULT_REGION",
"if",
"region",
".",
"empty?",
"image",
"=",
"DEFAULT_IMAGE",
"if",
"image",
".",
"empty?",
"size",
"=",
"DEFAULT_SIZE",
"if",
"size",
".",
"empty?",
"default_ssh_key",
"=",
"DEFAULT_SSH_KEY",
"if",
"ssh_key",
".",
"empty?",
"if",
"private_networking",
".",
"empty?",
"private_networking",
"=",
"DEFAULT_PRIVATE_NETWORKING",
"end",
"backups_enabled",
"=",
"DEFAULT_BACKUPS_ENABLED",
"if",
"backups_enabled",
".",
"empty?",
"ip6",
"=",
"DEFAULT_IP6",
"if",
"ip6",
".",
"empty?",
"timeout",
"=",
"DEFAULT_TIMEOUT",
"if",
"timeout",
".",
"empty?",
"require",
"'yaml'",
"File",
".",
"open",
"(",
"@path",
",",
"File",
"::",
"RDWR",
"|",
"File",
"::",
"TRUNC",
"|",
"File",
"::",
"CREAT",
",",
"0o600",
")",
"do",
"|",
"file",
"|",
"data",
"=",
"{",
"'authentication'",
"=>",
"{",
"'access_token'",
"=>",
"access_token",
"}",
",",
"'connection'",
"=>",
"{",
"'timeout'",
"=>",
"timeout",
"}",
",",
"'ssh'",
"=>",
"{",
"'ssh_user'",
"=>",
"ssh_user",
",",
"'ssh_key_path'",
"=>",
"ssh_key_path",
",",
"'ssh_port'",
"=>",
"ssh_port",
"}",
",",
"'defaults'",
"=>",
"{",
"'region'",
"=>",
"region",
",",
"'image'",
"=>",
"image",
",",
"'size'",
"=>",
"size",
",",
"'ssh_key'",
"=>",
"ssh_key",
",",
"'private_networking'",
"=>",
"private_networking",
",",
"'backups_enabled'",
"=>",
"backups_enabled",
",",
"'ip6'",
"=>",
"ip6",
"}",
"}",
"file",
".",
"write",
"data",
".",
"to_yaml",
"end",
"end"
] | Writes a config file | [
"Writes",
"a",
"config",
"file"
] | db1785c75f894022eb2ca3a7381f1d19cba4612f | https://github.com/petems/tugboat/blob/db1785c75f894022eb2ca3a7381f1d19cba4612f/lib/tugboat/config.rb#L114-L166 | train |
gocardless/creditsafe-ruby | lib/creditsafe/client.rb | Creditsafe.Client.handle_error | def handle_error(error)
case error
when Savon::SOAPFault
return UnknownApiError.new(error.message)
when Savon::HTTPError
if error.to_hash[:code] == 401
return AccountError.new("Unauthorized: invalid credentials")
end
return UnknownApiError.new(error.message)
when Excon::Errors::Error
return HttpError.new("Error making HTTP request: #{error.message}")
end
error
end | ruby | def handle_error(error)
case error
when Savon::SOAPFault
return UnknownApiError.new(error.message)
when Savon::HTTPError
if error.to_hash[:code] == 401
return AccountError.new("Unauthorized: invalid credentials")
end
return UnknownApiError.new(error.message)
when Excon::Errors::Error
return HttpError.new("Error making HTTP request: #{error.message}")
end
error
end | [
"def",
"handle_error",
"(",
"error",
")",
"case",
"error",
"when",
"Savon",
"::",
"SOAPFault",
"return",
"UnknownApiError",
".",
"new",
"(",
"error",
".",
"message",
")",
"when",
"Savon",
"::",
"HTTPError",
"if",
"error",
".",
"to_hash",
"[",
":code",
"]",
"==",
"401",
"return",
"AccountError",
".",
"new",
"(",
"\"Unauthorized: invalid credentials\"",
")",
"end",
"return",
"UnknownApiError",
".",
"new",
"(",
"error",
".",
"message",
")",
"when",
"Excon",
"::",
"Errors",
"::",
"Error",
"return",
"HttpError",
".",
"new",
"(",
"\"Error making HTTP request: #{error.message}\"",
")",
"end",
"error",
"end"
] | There's a potential bug in the creditsafe API where they actually return
an HTTP 401 if you're unauthorized, hence the sad special case below
rubocop:disable Metrics/MethodLength | [
"There",
"s",
"a",
"potential",
"bug",
"in",
"the",
"creditsafe",
"API",
"where",
"they",
"actually",
"return",
"an",
"HTTP",
"401",
"if",
"you",
"re",
"unauthorized",
"hence",
"the",
"sad",
"special",
"case",
"below"
] | 4a03027a18fddca0905f65fedae3ed6eb1bc05aa | https://github.com/gocardless/creditsafe-ruby/blob/4a03027a18fddca0905f65fedae3ed6eb1bc05aa/lib/creditsafe/client.rb#L116-L130 | train |
CrowdFlower/ruby-crowdflower | lib/crowdflower/base.rb | CrowdFlower.Connection.method_missing | def method_missing(method_id, *args)
if [:get, :post, :put, :delete].include?(method_id)
path, options = *args
options ||= {}
options[:query] = (default_params.merge(options[:query] || {}))
options[:headers] = (self.class.default_options[:headers].merge(options[:headers] || {}))
CrowdFlower.request_hook.call(method_id, path, options) do
self.class.send(method_id, url(path), options)
end
else
super
end
end | ruby | def method_missing(method_id, *args)
if [:get, :post, :put, :delete].include?(method_id)
path, options = *args
options ||= {}
options[:query] = (default_params.merge(options[:query] || {}))
options[:headers] = (self.class.default_options[:headers].merge(options[:headers] || {}))
CrowdFlower.request_hook.call(method_id, path, options) do
self.class.send(method_id, url(path), options)
end
else
super
end
end | [
"def",
"method_missing",
"(",
"method_id",
",",
"*",
"args",
")",
"if",
"[",
":get",
",",
":post",
",",
":put",
",",
":delete",
"]",
".",
"include?",
"(",
"method_id",
")",
"path",
",",
"options",
"=",
"args",
"options",
"||=",
"{",
"}",
"options",
"[",
":query",
"]",
"=",
"(",
"default_params",
".",
"merge",
"(",
"options",
"[",
":query",
"]",
"||",
"{",
"}",
")",
")",
"options",
"[",
":headers",
"]",
"=",
"(",
"self",
".",
"class",
".",
"default_options",
"[",
":headers",
"]",
".",
"merge",
"(",
"options",
"[",
":headers",
"]",
"||",
"{",
"}",
")",
")",
"CrowdFlower",
".",
"request_hook",
".",
"call",
"(",
"method_id",
",",
"path",
",",
"options",
")",
"do",
"self",
".",
"class",
".",
"send",
"(",
"method_id",
",",
"url",
"(",
"path",
")",
",",
"options",
")",
"end",
"else",
"super",
"end",
"end"
] | get, post, put and delete methods | [
"get",
"post",
"put",
"and",
"delete",
"methods"
] | 76e56343689cc2dff575bbe885e8269cdb236db0 | https://github.com/CrowdFlower/ruby-crowdflower/blob/76e56343689cc2dff575bbe885e8269cdb236db0/lib/crowdflower/base.rb#L67-L80 | train |
CrowdFlower/ruby-crowdflower | lib/crowdflower/judgment.rb | CrowdFlower.Judgment.all | def all(page = 1, limit = 100, latest = true)
opts = connection.version == 2 ? {:unseen => latest} : {:latest => latest}
connection.get(resource_uri, {:query => {:limit => limit, :page => page}.merge(opts)})
end | ruby | def all(page = 1, limit = 100, latest = true)
opts = connection.version == 2 ? {:unseen => latest} : {:latest => latest}
connection.get(resource_uri, {:query => {:limit => limit, :page => page}.merge(opts)})
end | [
"def",
"all",
"(",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
",",
"latest",
"=",
"true",
")",
"opts",
"=",
"connection",
".",
"version",
"==",
"2",
"?",
"{",
":unseen",
"=>",
"latest",
"}",
":",
"{",
":latest",
"=>",
"latest",
"}",
"connection",
".",
"get",
"(",
"resource_uri",
",",
"{",
":query",
"=>",
"{",
":limit",
"=>",
"limit",
",",
":page",
"=>",
"page",
"}",
".",
"merge",
"(",
"opts",
")",
"}",
")",
"end"
] | Pull every judgment | [
"Pull",
"every",
"judgment"
] | 76e56343689cc2dff575bbe885e8269cdb236db0 | https://github.com/CrowdFlower/ruby-crowdflower/blob/76e56343689cc2dff575bbe885e8269cdb236db0/lib/crowdflower/judgment.rb#L16-L19 | train |
samvera/solrizer | lib/solrizer/field_mapper.rb | Solrizer.FieldMapper.solr_names_and_values | def solr_names_and_values(field_name, field_value, index_types)
return {} if field_value.nil?
# Determine the set of index types
index_types = Array(index_types)
index_types.uniq!
index_types.dup.each do |index_type|
if index_type.to_s =~ /^not_(.*)/
index_types.delete index_type # not_foo
index_types.delete $1.to_sym # foo
end
end
# Map names and values
results = {}
# Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.
field_value = [field_value] if field_value.kind_of? Time
index_types.each do |index_type|
Array(field_value).each do |single_value|
# Get mapping for field
descriptor = indexer(index_type)
data_type = extract_type(single_value)
name, converter = descriptor.name_and_converter(field_name, type: data_type)
next unless name
# Is there a custom converter?
# TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.
value = if converter
if converter.arity == 1
converter.call(single_value)
else
converter.call(single_value, field_name)
end
elsif data_type == :boolean
single_value
else
single_value.to_s
end
# Add mapped name & value, unless it's a duplicate
if descriptor.evaluate_suffix(data_type).multivalued?
values = (results[name] ||= [])
values << value unless value.nil? || values.include?(value)
else
Solrizer.logger.warn "Setting #{name} to `#{value}', but it already had `#{results[name]}'" if results[name] && Solrizer.logger
results[name] = value
end
end
end
results
end | ruby | def solr_names_and_values(field_name, field_value, index_types)
return {} if field_value.nil?
# Determine the set of index types
index_types = Array(index_types)
index_types.uniq!
index_types.dup.each do |index_type|
if index_type.to_s =~ /^not_(.*)/
index_types.delete index_type # not_foo
index_types.delete $1.to_sym # foo
end
end
# Map names and values
results = {}
# Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.
field_value = [field_value] if field_value.kind_of? Time
index_types.each do |index_type|
Array(field_value).each do |single_value|
# Get mapping for field
descriptor = indexer(index_type)
data_type = extract_type(single_value)
name, converter = descriptor.name_and_converter(field_name, type: data_type)
next unless name
# Is there a custom converter?
# TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.
value = if converter
if converter.arity == 1
converter.call(single_value)
else
converter.call(single_value, field_name)
end
elsif data_type == :boolean
single_value
else
single_value.to_s
end
# Add mapped name & value, unless it's a duplicate
if descriptor.evaluate_suffix(data_type).multivalued?
values = (results[name] ||= [])
values << value unless value.nil? || values.include?(value)
else
Solrizer.logger.warn "Setting #{name} to `#{value}', but it already had `#{results[name]}'" if results[name] && Solrizer.logger
results[name] = value
end
end
end
results
end | [
"def",
"solr_names_and_values",
"(",
"field_name",
",",
"field_value",
",",
"index_types",
")",
"return",
"{",
"}",
"if",
"field_value",
".",
"nil?",
"# Determine the set of index types",
"index_types",
"=",
"Array",
"(",
"index_types",
")",
"index_types",
".",
"uniq!",
"index_types",
".",
"dup",
".",
"each",
"do",
"|",
"index_type",
"|",
"if",
"index_type",
".",
"to_s",
"=~",
"/",
"/",
"index_types",
".",
"delete",
"index_type",
"# not_foo",
"index_types",
".",
"delete",
"$1",
".",
"to_sym",
"# foo",
"end",
"end",
"# Map names and values",
"results",
"=",
"{",
"}",
"# Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.",
"field_value",
"=",
"[",
"field_value",
"]",
"if",
"field_value",
".",
"kind_of?",
"Time",
"index_types",
".",
"each",
"do",
"|",
"index_type",
"|",
"Array",
"(",
"field_value",
")",
".",
"each",
"do",
"|",
"single_value",
"|",
"# Get mapping for field",
"descriptor",
"=",
"indexer",
"(",
"index_type",
")",
"data_type",
"=",
"extract_type",
"(",
"single_value",
")",
"name",
",",
"converter",
"=",
"descriptor",
".",
"name_and_converter",
"(",
"field_name",
",",
"type",
":",
"data_type",
")",
"next",
"unless",
"name",
"# Is there a custom converter?",
"# TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.",
"value",
"=",
"if",
"converter",
"if",
"converter",
".",
"arity",
"==",
"1",
"converter",
".",
"call",
"(",
"single_value",
")",
"else",
"converter",
".",
"call",
"(",
"single_value",
",",
"field_name",
")",
"end",
"elsif",
"data_type",
"==",
":boolean",
"single_value",
"else",
"single_value",
".",
"to_s",
"end",
"# Add mapped name & value, unless it's a duplicate",
"if",
"descriptor",
".",
"evaluate_suffix",
"(",
"data_type",
")",
".",
"multivalued?",
"values",
"=",
"(",
"results",
"[",
"name",
"]",
"||=",
"[",
"]",
")",
"values",
"<<",
"value",
"unless",
"value",
".",
"nil?",
"||",
"values",
".",
"include?",
"(",
"value",
")",
"else",
"Solrizer",
".",
"logger",
".",
"warn",
"\"Setting #{name} to `#{value}', but it already had `#{results[name]}'\"",
"if",
"results",
"[",
"name",
"]",
"&&",
"Solrizer",
".",
"logger",
"results",
"[",
"name",
"]",
"=",
"value",
"end",
"end",
"end",
"results",
"end"
] | Given a field name-value pair, a data type, and an array of index types, returns a hash of
mapped names and values. The values in the hash are _arrays_, and may contain multiple values. | [
"Given",
"a",
"field",
"name",
"-",
"value",
"pair",
"a",
"data",
"type",
"and",
"an",
"array",
"of",
"index",
"types",
"returns",
"a",
"hash",
"of",
"mapped",
"names",
"and",
"values",
".",
"The",
"values",
"in",
"the",
"hash",
"are",
"_arrays_",
"and",
"may",
"contain",
"multiple",
"values",
"."
] | 6a53933cdc977a507342bbdde68a2165e3fd1263 | https://github.com/samvera/solrizer/blob/6a53933cdc977a507342bbdde68a2165e3fd1263/lib/solrizer/field_mapper.rb#L180-L235 | train |
anlek/mongify | lib/mongify/configuration.rb | Mongify.Configuration.mongodb_connection | def mongodb_connection(options={}, &block)
return @mongodb_conncetion if @mongodb_connection and !block_given?
options.stringify_keys!
options['adapter'] ||= 'mongodb'
@mongodb_connection = no_sql_connection(options, &block)
end | ruby | def mongodb_connection(options={}, &block)
return @mongodb_conncetion if @mongodb_connection and !block_given?
options.stringify_keys!
options['adapter'] ||= 'mongodb'
@mongodb_connection = no_sql_connection(options, &block)
end | [
"def",
"mongodb_connection",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"return",
"@mongodb_conncetion",
"if",
"@mongodb_connection",
"and",
"!",
"block_given?",
"options",
".",
"stringify_keys!",
"options",
"[",
"'adapter'",
"]",
"||=",
"'mongodb'",
"@mongodb_connection",
"=",
"no_sql_connection",
"(",
"options",
",",
"block",
")",
"end"
] | self
Returns a no_sql_connection which is bound to a mongodb adapter
or builds a new no_sql_connection if block is given | [
"self",
"Returns",
"a",
"no_sql_connection",
"which",
"is",
"bound",
"to",
"a",
"mongodb",
"adapter",
"or",
"builds",
"a",
"new",
"no_sql_connection",
"if",
"block",
"is",
"given"
] | 6c592e864bac04338fdc3d89b3413351d87505c2 | https://github.com/anlek/mongify/blob/6c592e864bac04338fdc3d89b3413351d87505c2/lib/mongify/configuration.rb#L22-L27 | train |
anlek/mongify | lib/mongify/progressbar.rb | Mongify.ProgressBar.show | def show
return unless @out
arguments = @format_arguments.map {|method|
method = sprintf("fmt_%s", method)
send(method)
}
line = sprintf(@format, *arguments)
width = get_width
if line.length == width - 1
@out.print(line + eol)
@out.flush
elsif line.length >= width
@terminal_width = [@terminal_width - (line.length - width + 1), 0].max
if @terminal_width == 0 then @out.print(line + eol) else show end
else # line.length < width - 1
@terminal_width += width - line.length + 1
show
end
@previous_time = Time.now
end | ruby | def show
return unless @out
arguments = @format_arguments.map {|method|
method = sprintf("fmt_%s", method)
send(method)
}
line = sprintf(@format, *arguments)
width = get_width
if line.length == width - 1
@out.print(line + eol)
@out.flush
elsif line.length >= width
@terminal_width = [@terminal_width - (line.length - width + 1), 0].max
if @terminal_width == 0 then @out.print(line + eol) else show end
else # line.length < width - 1
@terminal_width += width - line.length + 1
show
end
@previous_time = Time.now
end | [
"def",
"show",
"return",
"unless",
"@out",
"arguments",
"=",
"@format_arguments",
".",
"map",
"{",
"|",
"method",
"|",
"method",
"=",
"sprintf",
"(",
"\"fmt_%s\"",
",",
"method",
")",
"send",
"(",
"method",
")",
"}",
"line",
"=",
"sprintf",
"(",
"@format",
",",
"arguments",
")",
"width",
"=",
"get_width",
"if",
"line",
".",
"length",
"==",
"width",
"-",
"1",
"@out",
".",
"print",
"(",
"line",
"+",
"eol",
")",
"@out",
".",
"flush",
"elsif",
"line",
".",
"length",
">=",
"width",
"@terminal_width",
"=",
"[",
"@terminal_width",
"-",
"(",
"line",
".",
"length",
"-",
"width",
"+",
"1",
")",
",",
"0",
"]",
".",
"max",
"if",
"@terminal_width",
"==",
"0",
"then",
"@out",
".",
"print",
"(",
"line",
"+",
"eol",
")",
"else",
"show",
"end",
"else",
"# line.length < width - 1",
"@terminal_width",
"+=",
"width",
"-",
"line",
".",
"length",
"+",
"1",
"show",
"end",
"@previous_time",
"=",
"Time",
".",
"now",
"end"
] | Draws the bar | [
"Draws",
"the",
"bar"
] | 6c592e864bac04338fdc3d89b3413351d87505c2 | https://github.com/anlek/mongify/blob/6c592e864bac04338fdc3d89b3413351d87505c2/lib/mongify/progressbar.rb#L158-L178 | train |
railsware/rack_session_access | lib/rack_session_access/middleware.rb | RackSessionAccess.Middleware.call | def call(env)
return render(500) do |xml|
xml.h2("#{@key} env is not initialized")
end unless env[@key]
request = ::Rack::Request.new(env)
if action = dispatch_action(request)
send(action, request)
else
@app.call(env)
end
end | ruby | def call(env)
return render(500) do |xml|
xml.h2("#{@key} env is not initialized")
end unless env[@key]
request = ::Rack::Request.new(env)
if action = dispatch_action(request)
send(action, request)
else
@app.call(env)
end
end | [
"def",
"call",
"(",
"env",
")",
"return",
"render",
"(",
"500",
")",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"(",
"\"#{@key} env is not initialized\"",
")",
"end",
"unless",
"env",
"[",
"@key",
"]",
"request",
"=",
"::",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"if",
"action",
"=",
"dispatch_action",
"(",
"request",
")",
"send",
"(",
"action",
",",
"request",
")",
"else",
"@app",
".",
"call",
"(",
"env",
")",
"end",
"end"
] | Initialize RackSessionAccess middleware
@param app a rack application
@param options
Options:
* :key - rack session key | [
"Initialize",
"RackSessionAccess",
"middleware"
] | aa462368296f4ba9ced66360eb1de39acd3610c9 | https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L23-L35 | train |
railsware/rack_session_access | lib/rack_session_access/middleware.rb | RackSessionAccess.Middleware.show | def show(request)
# force load session because it can be lazy loaded
request.env[@key].delete(:rack_session_access_force_load_session)
# session hash object
session_hash = request.env[@key].to_hash
case File.extname(request.path)
when ".raw"
render do |xml|
xml.h2 "Raw rack session data"
xml.pre RackSessionAccess.encode(session_hash)
end
else
render do |xml|
xml.h2 "Rack session data"
xml.ul do |ul|
session_hash.each do |k,v|
ul.li("#{k.inspect} : #{v.inspect}")
end
end
xml.p do |p|
p.a("Edit", :href => action_path(:edit))
end
end
end
end | ruby | def show(request)
# force load session because it can be lazy loaded
request.env[@key].delete(:rack_session_access_force_load_session)
# session hash object
session_hash = request.env[@key].to_hash
case File.extname(request.path)
when ".raw"
render do |xml|
xml.h2 "Raw rack session data"
xml.pre RackSessionAccess.encode(session_hash)
end
else
render do |xml|
xml.h2 "Rack session data"
xml.ul do |ul|
session_hash.each do |k,v|
ul.li("#{k.inspect} : #{v.inspect}")
end
end
xml.p do |p|
p.a("Edit", :href => action_path(:edit))
end
end
end
end | [
"def",
"show",
"(",
"request",
")",
"# force load session because it can be lazy loaded",
"request",
".",
"env",
"[",
"@key",
"]",
".",
"delete",
"(",
":rack_session_access_force_load_session",
")",
"# session hash object",
"session_hash",
"=",
"request",
".",
"env",
"[",
"@key",
"]",
".",
"to_hash",
"case",
"File",
".",
"extname",
"(",
"request",
".",
"path",
")",
"when",
"\".raw\"",
"render",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"\"Raw rack session data\"",
"xml",
".",
"pre",
"RackSessionAccess",
".",
"encode",
"(",
"session_hash",
")",
"end",
"else",
"render",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"\"Rack session data\"",
"xml",
".",
"ul",
"do",
"|",
"ul",
"|",
"session_hash",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"ul",
".",
"li",
"(",
"\"#{k.inspect} : #{v.inspect}\"",
")",
"end",
"end",
"xml",
".",
"p",
"do",
"|",
"p",
"|",
"p",
".",
"a",
"(",
"\"Edit\"",
",",
":href",
"=>",
"action_path",
"(",
":edit",
")",
")",
"end",
"end",
"end",
"end"
] | List session data | [
"List",
"session",
"data"
] | aa462368296f4ba9ced66360eb1de39acd3610c9 | https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L40-L66 | train |
railsware/rack_session_access | lib/rack_session_access/middleware.rb | RackSessionAccess.Middleware.edit | def edit(request)
render do |xml|
xml.h2 "Update rack session"
xml.p "Put marshalized and encoded with base64 ruby hash into the form"
xml.form({
:action => action_path(:update),
:method => 'post',
:enctype => 'application/x-www-form-urlencoded'
}) do |form|
form.input(:type => 'hidden', :name =>'_method', :value => 'put')
form.textarea(:cols => 40, :rows => 10, :name => 'data') {}
form.p do |p|
p.input(:type => 'submit', :value => "Update")
end
end
end
end | ruby | def edit(request)
render do |xml|
xml.h2 "Update rack session"
xml.p "Put marshalized and encoded with base64 ruby hash into the form"
xml.form({
:action => action_path(:update),
:method => 'post',
:enctype => 'application/x-www-form-urlencoded'
}) do |form|
form.input(:type => 'hidden', :name =>'_method', :value => 'put')
form.textarea(:cols => 40, :rows => 10, :name => 'data') {}
form.p do |p|
p.input(:type => 'submit', :value => "Update")
end
end
end
end | [
"def",
"edit",
"(",
"request",
")",
"render",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"\"Update rack session\"",
"xml",
".",
"p",
"\"Put marshalized and encoded with base64 ruby hash into the form\"",
"xml",
".",
"form",
"(",
"{",
":action",
"=>",
"action_path",
"(",
":update",
")",
",",
":method",
"=>",
"'post'",
",",
":enctype",
"=>",
"'application/x-www-form-urlencoded'",
"}",
")",
"do",
"|",
"form",
"|",
"form",
".",
"input",
"(",
":type",
"=>",
"'hidden'",
",",
":name",
"=>",
"'_method'",
",",
":value",
"=>",
"'put'",
")",
"form",
".",
"textarea",
"(",
":cols",
"=>",
"40",
",",
":rows",
"=>",
"10",
",",
":name",
"=>",
"'data'",
")",
"{",
"}",
"form",
".",
"p",
"do",
"|",
"p",
"|",
"p",
".",
"input",
"(",
":type",
"=>",
"'submit'",
",",
":value",
"=>",
"\"Update\"",
")",
"end",
"end",
"end",
"end"
] | Render form for submit new session data | [
"Render",
"form",
"for",
"submit",
"new",
"session",
"data"
] | aa462368296f4ba9ced66360eb1de39acd3610c9 | https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L69-L85 | train |
railsware/rack_session_access | lib/rack_session_access/middleware.rb | RackSessionAccess.Middleware.update | def update(request)
begin
data = request.params['data']
hash = RackSessionAccess.decode(data)
hash.each { |k, v| request.env[@key][k] = v }
rescue => e
return render(400) do |xml|
xml.h2("Bad data #{data.inspect}: #{e.message} ")
end
end
redirect_to action_path(:show)
end | ruby | def update(request)
begin
data = request.params['data']
hash = RackSessionAccess.decode(data)
hash.each { |k, v| request.env[@key][k] = v }
rescue => e
return render(400) do |xml|
xml.h2("Bad data #{data.inspect}: #{e.message} ")
end
end
redirect_to action_path(:show)
end | [
"def",
"update",
"(",
"request",
")",
"begin",
"data",
"=",
"request",
".",
"params",
"[",
"'data'",
"]",
"hash",
"=",
"RackSessionAccess",
".",
"decode",
"(",
"data",
")",
"hash",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"request",
".",
"env",
"[",
"@key",
"]",
"[",
"k",
"]",
"=",
"v",
"}",
"rescue",
"=>",
"e",
"return",
"render",
"(",
"400",
")",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"(",
"\"Bad data #{data.inspect}: #{e.message} \"",
")",
"end",
"end",
"redirect_to",
"action_path",
"(",
":show",
")",
"end"
] | Update session data | [
"Update",
"session",
"data"
] | aa462368296f4ba9ced66360eb1de39acd3610c9 | https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L88-L100 | train |
railsware/rack_session_access | lib/rack_session_access/middleware.rb | RackSessionAccess.Middleware.dispatch_action | def dispatch_action(request)
method = request_method(request)
path = request.path.sub(/\.\w+$/, '')
route = @routing.detect { |r| r[0] == method && r[1] == path }
route[2] if route
end | ruby | def dispatch_action(request)
method = request_method(request)
path = request.path.sub(/\.\w+$/, '')
route = @routing.detect { |r| r[0] == method && r[1] == path }
route[2] if route
end | [
"def",
"dispatch_action",
"(",
"request",
")",
"method",
"=",
"request_method",
"(",
"request",
")",
"path",
"=",
"request",
".",
"path",
".",
"sub",
"(",
"/",
"\\.",
"\\w",
"/",
",",
"''",
")",
"route",
"=",
"@routing",
".",
"detect",
"{",
"|",
"r",
"|",
"r",
"[",
"0",
"]",
"==",
"method",
"&&",
"r",
"[",
"1",
"]",
"==",
"path",
"}",
"route",
"[",
"2",
"]",
"if",
"route",
"end"
] | Dispatch action from request | [
"Dispatch",
"action",
"from",
"request"
] | aa462368296f4ba9ced66360eb1de39acd3610c9 | https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L105-L110 | train |
railsware/rack_session_access | lib/rack_session_access/middleware.rb | RackSessionAccess.Middleware.request_method | def request_method(request)
return request.request_method if request.request_method != 'POST'
return request.params['_method'].upcase if request.params['_method']
request.request_method
end | ruby | def request_method(request)
return request.request_method if request.request_method != 'POST'
return request.params['_method'].upcase if request.params['_method']
request.request_method
end | [
"def",
"request_method",
"(",
"request",
")",
"return",
"request",
".",
"request_method",
"if",
"request",
".",
"request_method",
"!=",
"'POST'",
"return",
"request",
".",
"params",
"[",
"'_method'",
"]",
".",
"upcase",
"if",
"request",
".",
"params",
"[",
"'_method'",
"]",
"request",
".",
"request_method",
"end"
] | Return HTTP method, detect emulated method with _method param | [
"Return",
"HTTP",
"method",
"detect",
"emulated",
"method",
"with",
"_method",
"param"
] | aa462368296f4ba9ced66360eb1de39acd3610c9 | https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L113-L117 | train |
bdmac/strong_password | lib/strong_password/qwerty_adjuster.rb | StrongPassword.QwertyAdjuster.adjusted_entropy | def adjusted_entropy(entropy_threshhold: 0)
revpassword = base_password.reverse
min_entropy = [EntropyCalculator.calculate(base_password), EntropyCalculator.calculate(revpassword)].min
QWERTY_STRINGS.each do |qwertystr|
qpassword = mask_qwerty_strings(base_password, qwertystr)
qrevpassword = mask_qwerty_strings(revpassword, qwertystr)
if qpassword != base_password
numbits = EntropyCalculator.calculate(qpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
if qrevpassword != revpassword
numbits = EntropyCalculator.calculate(qrevpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
end
min_entropy
end | ruby | def adjusted_entropy(entropy_threshhold: 0)
revpassword = base_password.reverse
min_entropy = [EntropyCalculator.calculate(base_password), EntropyCalculator.calculate(revpassword)].min
QWERTY_STRINGS.each do |qwertystr|
qpassword = mask_qwerty_strings(base_password, qwertystr)
qrevpassword = mask_qwerty_strings(revpassword, qwertystr)
if qpassword != base_password
numbits = EntropyCalculator.calculate(qpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
if qrevpassword != revpassword
numbits = EntropyCalculator.calculate(qrevpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
end
min_entropy
end | [
"def",
"adjusted_entropy",
"(",
"entropy_threshhold",
":",
"0",
")",
"revpassword",
"=",
"base_password",
".",
"reverse",
"min_entropy",
"=",
"[",
"EntropyCalculator",
".",
"calculate",
"(",
"base_password",
")",
",",
"EntropyCalculator",
".",
"calculate",
"(",
"revpassword",
")",
"]",
".",
"min",
"QWERTY_STRINGS",
".",
"each",
"do",
"|",
"qwertystr",
"|",
"qpassword",
"=",
"mask_qwerty_strings",
"(",
"base_password",
",",
"qwertystr",
")",
"qrevpassword",
"=",
"mask_qwerty_strings",
"(",
"revpassword",
",",
"qwertystr",
")",
"if",
"qpassword",
"!=",
"base_password",
"numbits",
"=",
"EntropyCalculator",
".",
"calculate",
"(",
"qpassword",
")",
"min_entropy",
"=",
"[",
"min_entropy",
",",
"numbits",
"]",
".",
"min",
"return",
"min_entropy",
"if",
"min_entropy",
"<",
"entropy_threshhold",
"end",
"if",
"qrevpassword",
"!=",
"revpassword",
"numbits",
"=",
"EntropyCalculator",
".",
"calculate",
"(",
"qrevpassword",
")",
"min_entropy",
"=",
"[",
"min_entropy",
",",
"numbits",
"]",
".",
"min",
"return",
"min_entropy",
"if",
"min_entropy",
"<",
"entropy_threshhold",
"end",
"end",
"min_entropy",
"end"
] | Returns the minimum entropy for the password's qwerty locality
adjustments. If a threshhold is specified we will bail
early to avoid unnecessary processing. | [
"Returns",
"the",
"minimum",
"entropy",
"for",
"the",
"password",
"s",
"qwerty",
"locality",
"adjustments",
".",
"If",
"a",
"threshhold",
"is",
"specified",
"we",
"will",
"bail",
"early",
"to",
"avoid",
"unnecessary",
"processing",
"."
] | b7f87281c7e2755a2df63bce5a8336755b3954e2 | https://github.com/bdmac/strong_password/blob/b7f87281c7e2755a2df63bce5a8336755b3954e2/lib/strong_password/qwerty_adjuster.rb#L37-L55 | train |
bdmac/strong_password | lib/strong_password/dictionary_adjuster.rb | StrongPassword.DictionaryAdjuster.adjusted_entropy | def adjusted_entropy(min_word_length: 4, extra_dictionary_words: [], entropy_threshhold: -1)
dictionary_words = Regexp.union( ( extra_dictionary_words + COMMON_PASSWORDS ).compact.reject{ |i| i.length < min_word_length } )
min_entropy = EntropyCalculator.calculate(base_password)
# Process the passwords, while looking for possible matching words in the dictionary.
PasswordVariants.all_variants(base_password).inject( min_entropy ) do |min_entropy, variant|
[ min_entropy, EntropyCalculator.calculate( variant.sub( dictionary_words, '*' ) ) ].min
end
end | ruby | def adjusted_entropy(min_word_length: 4, extra_dictionary_words: [], entropy_threshhold: -1)
dictionary_words = Regexp.union( ( extra_dictionary_words + COMMON_PASSWORDS ).compact.reject{ |i| i.length < min_word_length } )
min_entropy = EntropyCalculator.calculate(base_password)
# Process the passwords, while looking for possible matching words in the dictionary.
PasswordVariants.all_variants(base_password).inject( min_entropy ) do |min_entropy, variant|
[ min_entropy, EntropyCalculator.calculate( variant.sub( dictionary_words, '*' ) ) ].min
end
end | [
"def",
"adjusted_entropy",
"(",
"min_word_length",
":",
"4",
",",
"extra_dictionary_words",
":",
"[",
"]",
",",
"entropy_threshhold",
":",
"-",
"1",
")",
"dictionary_words",
"=",
"Regexp",
".",
"union",
"(",
"(",
"extra_dictionary_words",
"+",
"COMMON_PASSWORDS",
")",
".",
"compact",
".",
"reject",
"{",
"|",
"i",
"|",
"i",
".",
"length",
"<",
"min_word_length",
"}",
")",
"min_entropy",
"=",
"EntropyCalculator",
".",
"calculate",
"(",
"base_password",
")",
"# Process the passwords, while looking for possible matching words in the dictionary.",
"PasswordVariants",
".",
"all_variants",
"(",
"base_password",
")",
".",
"inject",
"(",
"min_entropy",
")",
"do",
"|",
"min_entropy",
",",
"variant",
"|",
"[",
"min_entropy",
",",
"EntropyCalculator",
".",
"calculate",
"(",
"variant",
".",
"sub",
"(",
"dictionary_words",
",",
"'*'",
")",
")",
"]",
".",
"min",
"end",
"end"
] | Returns the minimum entropy for the passwords dictionary adjustments.
If a threshhold is specified we will bail early to avoid unnecessary
processing.
Note that we only check for the first matching word up to the threshhold if set.
Subsequent matching words are not deductd. | [
"Returns",
"the",
"minimum",
"entropy",
"for",
"the",
"passwords",
"dictionary",
"adjustments",
".",
"If",
"a",
"threshhold",
"is",
"specified",
"we",
"will",
"bail",
"early",
"to",
"avoid",
"unnecessary",
"processing",
".",
"Note",
"that",
"we",
"only",
"check",
"for",
"the",
"first",
"matching",
"word",
"up",
"to",
"the",
"threshhold",
"if",
"set",
".",
"Subsequent",
"matching",
"words",
"are",
"not",
"deductd",
"."
] | b7f87281c7e2755a2df63bce5a8336755b3954e2 | https://github.com/bdmac/strong_password/blob/b7f87281c7e2755a2df63bce5a8336755b3954e2/lib/strong_password/dictionary_adjuster.rb#L991-L998 | train |
dkubb/adamantium | lib/adamantium/module_methods.rb | Adamantium.ModuleMethods.memoize | def memoize(*methods)
options = methods.last.kind_of?(Hash) ? methods.pop : {}
method_freezer = Freezer.parse(options) || freezer
methods.each { |method| memoize_method(method, method_freezer) }
self
end | ruby | def memoize(*methods)
options = methods.last.kind_of?(Hash) ? methods.pop : {}
method_freezer = Freezer.parse(options) || freezer
methods.each { |method| memoize_method(method, method_freezer) }
self
end | [
"def",
"memoize",
"(",
"*",
"methods",
")",
"options",
"=",
"methods",
".",
"last",
".",
"kind_of?",
"(",
"Hash",
")",
"?",
"methods",
".",
"pop",
":",
"{",
"}",
"method_freezer",
"=",
"Freezer",
".",
"parse",
"(",
"options",
")",
"||",
"freezer",
"methods",
".",
"each",
"{",
"|",
"method",
"|",
"memoize_method",
"(",
"method",
",",
"method_freezer",
")",
"}",
"self",
"end"
] | Memoize a list of methods
@example
memoize :hash
@param [Array<#to_s>] methods
a list of methods to memoize
@return [self]
@api public | [
"Memoize",
"a",
"list",
"of",
"methods"
] | bf38d4ad8a4307ab7f0593758b87f62b91e1df69 | https://github.com/dkubb/adamantium/blob/bf38d4ad8a4307ab7f0593758b87f62b91e1df69/lib/adamantium/module_methods.rb#L28-L33 | train |
dkubb/adamantium | lib/adamantium/module_methods.rb | Adamantium.ModuleMethods.memoize_method | def memoize_method(method_name, freezer)
memoized_methods[method_name] = Memoizable::MethodBuilder
.new(self, method_name, freezer).call
end | ruby | def memoize_method(method_name, freezer)
memoized_methods[method_name] = Memoizable::MethodBuilder
.new(self, method_name, freezer).call
end | [
"def",
"memoize_method",
"(",
"method_name",
",",
"freezer",
")",
"memoized_methods",
"[",
"method_name",
"]",
"=",
"Memoizable",
"::",
"MethodBuilder",
".",
"new",
"(",
"self",
",",
"method_name",
",",
"freezer",
")",
".",
"call",
"end"
] | Memoize the named method
@param [Symbol] method_name
a method name to memoize
@param [#call] freezer
a callable object to freeze the value
@return [undefined]
@api private | [
"Memoize",
"the",
"named",
"method"
] | bf38d4ad8a4307ab7f0593758b87f62b91e1df69 | https://github.com/dkubb/adamantium/blob/bf38d4ad8a4307ab7f0593758b87f62b91e1df69/lib/adamantium/module_methods.rb#L60-L63 | train |
propublica/timeline-setter | lib/timeline_setter/timeline.rb | TimelineSetter.Timeline.timeline_min | def timeline_min
@js = ""
@css = Kompress::CSS.new(File.open("#{TimelineSetter::ROOT}/public/stylesheets/timeline-setter.css").read).css
libs = Dir.glob("#{TimelineSetter::ROOT}/public/javascripts/vendor/**").select {|q| q =~ /min/ }
libs.each { |lib| @js << File.open(lib,'r').read }
@min_html = Kompress::HTML.new(timeline_markup).html
@js << File.open("#{TimelineSetter::ROOT}/public/javascripts/timeline-setter.min.js", 'r').read
@timeline = tmpl("timeline-min.erb")
end | ruby | def timeline_min
@js = ""
@css = Kompress::CSS.new(File.open("#{TimelineSetter::ROOT}/public/stylesheets/timeline-setter.css").read).css
libs = Dir.glob("#{TimelineSetter::ROOT}/public/javascripts/vendor/**").select {|q| q =~ /min/ }
libs.each { |lib| @js << File.open(lib,'r').read }
@min_html = Kompress::HTML.new(timeline_markup).html
@js << File.open("#{TimelineSetter::ROOT}/public/javascripts/timeline-setter.min.js", 'r').read
@timeline = tmpl("timeline-min.erb")
end | [
"def",
"timeline_min",
"@js",
"=",
"\"\"",
"@css",
"=",
"Kompress",
"::",
"CSS",
".",
"new",
"(",
"File",
".",
"open",
"(",
"\"#{TimelineSetter::ROOT}/public/stylesheets/timeline-setter.css\"",
")",
".",
"read",
")",
".",
"css",
"libs",
"=",
"Dir",
".",
"glob",
"(",
"\"#{TimelineSetter::ROOT}/public/javascripts/vendor/**\"",
")",
".",
"select",
"{",
"|",
"q",
"|",
"q",
"=~",
"/",
"/",
"}",
"libs",
".",
"each",
"{",
"|",
"lib",
"|",
"@js",
"<<",
"File",
".",
"open",
"(",
"lib",
",",
"'r'",
")",
".",
"read",
"}",
"@min_html",
"=",
"Kompress",
"::",
"HTML",
".",
"new",
"(",
"timeline_markup",
")",
".",
"html",
"@js",
"<<",
"File",
".",
"open",
"(",
"\"#{TimelineSetter::ROOT}/public/javascripts/timeline-setter.min.js\"",
",",
"'r'",
")",
".",
"read",
"@timeline",
"=",
"tmpl",
"(",
"\"timeline-min.erb\"",
")",
"end"
] | Create a minified one-page version of a timeline by minifying CSS and JS and embedding all assets
into our ERB template. | [
"Create",
"a",
"minified",
"one",
"-",
"page",
"version",
"of",
"a",
"timeline",
"by",
"minifying",
"CSS",
"and",
"JS",
"and",
"embedding",
"all",
"assets",
"into",
"our",
"ERB",
"template",
"."
] | a6229c8942a2eddfab9b957cee02f33176f00ab9 | https://github.com/propublica/timeline-setter/blob/a6229c8942a2eddfab9b957cee02f33176f00ab9/lib/timeline_setter/timeline.rb#L38-L46 | train |
eapache/starscope | lib/starscope/db.rb | Starscope.DB.parse_db | def parse_db(stream)
case stream.gets.to_i
when DB_FORMAT
@meta = Oj.load(stream.gets)
@tables = Oj.load(stream.gets)
return true
when 3..4
# Old format, so read the directories segment then rebuild
add_paths(Oj.load(stream.gets))
return false
when 0..2
# Old format (pre-json), so read the directories segment then rebuild
len = stream.gets.to_i
add_paths(Marshal.load(stream.read(len)))
return false
else
raise UnknownDBFormatError
end
rescue Oj::ParseError
stream.rewind
raise unless stream.gets.to_i == DB_FORMAT
# try reading as formated json, which is much slower, but it is sometimes
# useful to be able to directly read your db
objects = []
Oj.load(stream) { |obj| objects << obj }
@meta, @tables = objects
return true
end | ruby | def parse_db(stream)
case stream.gets.to_i
when DB_FORMAT
@meta = Oj.load(stream.gets)
@tables = Oj.load(stream.gets)
return true
when 3..4
# Old format, so read the directories segment then rebuild
add_paths(Oj.load(stream.gets))
return false
when 0..2
# Old format (pre-json), so read the directories segment then rebuild
len = stream.gets.to_i
add_paths(Marshal.load(stream.read(len)))
return false
else
raise UnknownDBFormatError
end
rescue Oj::ParseError
stream.rewind
raise unless stream.gets.to_i == DB_FORMAT
# try reading as formated json, which is much slower, but it is sometimes
# useful to be able to directly read your db
objects = []
Oj.load(stream) { |obj| objects << obj }
@meta, @tables = objects
return true
end | [
"def",
"parse_db",
"(",
"stream",
")",
"case",
"stream",
".",
"gets",
".",
"to_i",
"when",
"DB_FORMAT",
"@meta",
"=",
"Oj",
".",
"load",
"(",
"stream",
".",
"gets",
")",
"@tables",
"=",
"Oj",
".",
"load",
"(",
"stream",
".",
"gets",
")",
"return",
"true",
"when",
"3",
"..",
"4",
"# Old format, so read the directories segment then rebuild",
"add_paths",
"(",
"Oj",
".",
"load",
"(",
"stream",
".",
"gets",
")",
")",
"return",
"false",
"when",
"0",
"..",
"2",
"# Old format (pre-json), so read the directories segment then rebuild",
"len",
"=",
"stream",
".",
"gets",
".",
"to_i",
"add_paths",
"(",
"Marshal",
".",
"load",
"(",
"stream",
".",
"read",
"(",
"len",
")",
")",
")",
"return",
"false",
"else",
"raise",
"UnknownDBFormatError",
"end",
"rescue",
"Oj",
"::",
"ParseError",
"stream",
".",
"rewind",
"raise",
"unless",
"stream",
".",
"gets",
".",
"to_i",
"==",
"DB_FORMAT",
"# try reading as formated json, which is much slower, but it is sometimes",
"# useful to be able to directly read your db",
"objects",
"=",
"[",
"]",
"Oj",
".",
"load",
"(",
"stream",
")",
"{",
"|",
"obj",
"|",
"objects",
"<<",
"obj",
"}",
"@meta",
",",
"@tables",
"=",
"objects",
"return",
"true",
"end"
] | returns true iff the database is in the most recent format | [
"returns",
"true",
"iff",
"the",
"database",
"is",
"in",
"the",
"most",
"recent",
"format"
] | 8637f52bca46a5d5843789b7effd142a4586185f | https://github.com/eapache/starscope/blob/8637f52bca46a5d5843789b7effd142a4586185f/lib/starscope/db.rb#L164-L191 | train |
jellymann/mittsu | lib/mittsu/extras/geometries/polyhedron_geometry.rb | Mittsu.PolyhedronGeometry.prepare | def prepare(vector)
vertex = vector.normalize.clone
vertex.index = @vertices.push(vertex).length - 1
# Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
u = azimuth(vector) / 2.0 / Math::PI + 0.5
v = inclination(vector) / Math::PI + 0.5
vertex.uv = Vector2.new(u, 1.0 - v)
vertex
end | ruby | def prepare(vector)
vertex = vector.normalize.clone
vertex.index = @vertices.push(vertex).length - 1
# Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
u = azimuth(vector) / 2.0 / Math::PI + 0.5
v = inclination(vector) / Math::PI + 0.5
vertex.uv = Vector2.new(u, 1.0 - v)
vertex
end | [
"def",
"prepare",
"(",
"vector",
")",
"vertex",
"=",
"vector",
".",
"normalize",
".",
"clone",
"vertex",
".",
"index",
"=",
"@vertices",
".",
"push",
"(",
"vertex",
")",
".",
"length",
"-",
"1",
"# Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.",
"u",
"=",
"azimuth",
"(",
"vector",
")",
"/",
"2.0",
"/",
"Math",
"::",
"PI",
"+",
"0.5",
"v",
"=",
"inclination",
"(",
"vector",
")",
"/",
"Math",
"::",
"PI",
"+",
"0.5",
"vertex",
".",
"uv",
"=",
"Vector2",
".",
"new",
"(",
"u",
",",
"1.0",
"-",
"v",
")",
"vertex",
"end"
] | Project vector onto sphere's surface | [
"Project",
"vector",
"onto",
"sphere",
"s",
"surface"
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L76-L86 | train |
jellymann/mittsu | lib/mittsu/extras/geometries/polyhedron_geometry.rb | Mittsu.PolyhedronGeometry.make | def make(v1, v2, v3)
face = Face3.new(v1.index, v2.index, v3.index, [v1.clone, v2.clone, v3.clone])
@faces << face
@centroid.copy(v1).add(v2).add(v3).divide_scalar(3)
azi = azimuth(@centroid)
@face_vertex_uvs[0] << [
correct_uv(v1.uv, v1, azi),
correct_uv(v2.uv, v2, azi),
correct_uv(v3.uv, v3, azi)
]
end | ruby | def make(v1, v2, v3)
face = Face3.new(v1.index, v2.index, v3.index, [v1.clone, v2.clone, v3.clone])
@faces << face
@centroid.copy(v1).add(v2).add(v3).divide_scalar(3)
azi = azimuth(@centroid)
@face_vertex_uvs[0] << [
correct_uv(v1.uv, v1, azi),
correct_uv(v2.uv, v2, azi),
correct_uv(v3.uv, v3, azi)
]
end | [
"def",
"make",
"(",
"v1",
",",
"v2",
",",
"v3",
")",
"face",
"=",
"Face3",
".",
"new",
"(",
"v1",
".",
"index",
",",
"v2",
".",
"index",
",",
"v3",
".",
"index",
",",
"[",
"v1",
".",
"clone",
",",
"v2",
".",
"clone",
",",
"v3",
".",
"clone",
"]",
")",
"@faces",
"<<",
"face",
"@centroid",
".",
"copy",
"(",
"v1",
")",
".",
"add",
"(",
"v2",
")",
".",
"add",
"(",
"v3",
")",
".",
"divide_scalar",
"(",
"3",
")",
"azi",
"=",
"azimuth",
"(",
"@centroid",
")",
"@face_vertex_uvs",
"[",
"0",
"]",
"<<",
"[",
"correct_uv",
"(",
"v1",
".",
"uv",
",",
"v1",
",",
"azi",
")",
",",
"correct_uv",
"(",
"v2",
".",
"uv",
",",
"v2",
",",
"azi",
")",
",",
"correct_uv",
"(",
"v3",
".",
"uv",
",",
"v3",
",",
"azi",
")",
"]",
"end"
] | Approximate a curved face with recursively sub-divided triangles. | [
"Approximate",
"a",
"curved",
"face",
"with",
"recursively",
"sub",
"-",
"divided",
"triangles",
"."
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L89-L102 | train |
jellymann/mittsu | lib/mittsu/extras/geometries/polyhedron_geometry.rb | Mittsu.PolyhedronGeometry.subdivide | def subdivide(face, detail)
cols = 2.0 ** detail
a = prepare(@vertices[face.a])
b = prepare(@vertices[face.b])
c = prepare(@vertices[face.c])
v = []
# Construct all of the vertices for this subdivision.
for i in 0..cols do
v[i] = []
aj = prepare(a.clone.lerp(c, i.to_f / cols.to_f))
bj = prepare(b.clone.lerp(c, i.to_f / cols.to_f))
rows = cols - i
for j in 0..rows do
v[i][j] = if j.zero? && i == cols
aj
else
prepare(aj.clone.lerp(bj, j.to_f / rows.to_f))
end
end
end
# Construct all of the faces
for i in 0...cols do
for j in (0...(2 * (cols - i) - 1)) do
k = j/2
if j.even?
make(
v[i][k + 1],
v[i + 1][k],
v[i][k]
)
else
make(
v[i][k + 1],
v[i + 1][k + 1],
v[i + 1][k]
)
end
end
end
end | ruby | def subdivide(face, detail)
cols = 2.0 ** detail
a = prepare(@vertices[face.a])
b = prepare(@vertices[face.b])
c = prepare(@vertices[face.c])
v = []
# Construct all of the vertices for this subdivision.
for i in 0..cols do
v[i] = []
aj = prepare(a.clone.lerp(c, i.to_f / cols.to_f))
bj = prepare(b.clone.lerp(c, i.to_f / cols.to_f))
rows = cols - i
for j in 0..rows do
v[i][j] = if j.zero? && i == cols
aj
else
prepare(aj.clone.lerp(bj, j.to_f / rows.to_f))
end
end
end
# Construct all of the faces
for i in 0...cols do
for j in (0...(2 * (cols - i) - 1)) do
k = j/2
if j.even?
make(
v[i][k + 1],
v[i + 1][k],
v[i][k]
)
else
make(
v[i][k + 1],
v[i + 1][k + 1],
v[i + 1][k]
)
end
end
end
end | [
"def",
"subdivide",
"(",
"face",
",",
"detail",
")",
"cols",
"=",
"2.0",
"**",
"detail",
"a",
"=",
"prepare",
"(",
"@vertices",
"[",
"face",
".",
"a",
"]",
")",
"b",
"=",
"prepare",
"(",
"@vertices",
"[",
"face",
".",
"b",
"]",
")",
"c",
"=",
"prepare",
"(",
"@vertices",
"[",
"face",
".",
"c",
"]",
")",
"v",
"=",
"[",
"]",
"# Construct all of the vertices for this subdivision.",
"for",
"i",
"in",
"0",
"..",
"cols",
"do",
"v",
"[",
"i",
"]",
"=",
"[",
"]",
"aj",
"=",
"prepare",
"(",
"a",
".",
"clone",
".",
"lerp",
"(",
"c",
",",
"i",
".",
"to_f",
"/",
"cols",
".",
"to_f",
")",
")",
"bj",
"=",
"prepare",
"(",
"b",
".",
"clone",
".",
"lerp",
"(",
"c",
",",
"i",
".",
"to_f",
"/",
"cols",
".",
"to_f",
")",
")",
"rows",
"=",
"cols",
"-",
"i",
"for",
"j",
"in",
"0",
"..",
"rows",
"do",
"v",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"if",
"j",
".",
"zero?",
"&&",
"i",
"==",
"cols",
"aj",
"else",
"prepare",
"(",
"aj",
".",
"clone",
".",
"lerp",
"(",
"bj",
",",
"j",
".",
"to_f",
"/",
"rows",
".",
"to_f",
")",
")",
"end",
"end",
"end",
"# Construct all of the faces",
"for",
"i",
"in",
"0",
"...",
"cols",
"do",
"for",
"j",
"in",
"(",
"0",
"...",
"(",
"2",
"*",
"(",
"cols",
"-",
"i",
")",
"-",
"1",
")",
")",
"do",
"k",
"=",
"j",
"/",
"2",
"if",
"j",
".",
"even?",
"make",
"(",
"v",
"[",
"i",
"]",
"[",
"k",
"+",
"1",
"]",
",",
"v",
"[",
"i",
"+",
"1",
"]",
"[",
"k",
"]",
",",
"v",
"[",
"i",
"]",
"[",
"k",
"]",
")",
"else",
"make",
"(",
"v",
"[",
"i",
"]",
"[",
"k",
"+",
"1",
"]",
",",
"v",
"[",
"i",
"+",
"1",
"]",
"[",
"k",
"+",
"1",
"]",
",",
"v",
"[",
"i",
"+",
"1",
"]",
"[",
"k",
"]",
")",
"end",
"end",
"end",
"end"
] | Analytically subdivide a face to the required detail level. | [
"Analytically",
"subdivide",
"a",
"face",
"to",
"the",
"required",
"detail",
"level",
"."
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L105-L149 | train |
jellymann/mittsu | lib/mittsu/extras/geometries/polyhedron_geometry.rb | Mittsu.PolyhedronGeometry.inclination | def inclination(vector)
Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z))
end | ruby | def inclination(vector)
Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z))
end | [
"def",
"inclination",
"(",
"vector",
")",
"Math",
".",
"atan2",
"(",
"-",
"vector",
".",
"y",
",",
"Math",
".",
"sqrt",
"(",
"vector",
".",
"x",
"*",
"vector",
".",
"x",
"+",
"vector",
".",
"z",
"*",
"vector",
".",
"z",
")",
")",
"end"
] | Angle above the XZ plane. | [
"Angle",
"above",
"the",
"XZ",
"plane",
"."
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L157-L159 | train |
jellymann/mittsu | lib/mittsu/extras/geometries/polyhedron_geometry.rb | Mittsu.PolyhedronGeometry.correct_uv | def correct_uv(uv, vector, azimuth)
return Vector2.new(uv.x - 1.0, uv.y) if azimuth < 0
return Vector2.new(azimuth / 2.0 / Math::PI + 0.5, uv.y) if vector.x.zero? && vector.z.zero?
uv.clone
end | ruby | def correct_uv(uv, vector, azimuth)
return Vector2.new(uv.x - 1.0, uv.y) if azimuth < 0
return Vector2.new(azimuth / 2.0 / Math::PI + 0.5, uv.y) if vector.x.zero? && vector.z.zero?
uv.clone
end | [
"def",
"correct_uv",
"(",
"uv",
",",
"vector",
",",
"azimuth",
")",
"return",
"Vector2",
".",
"new",
"(",
"uv",
".",
"x",
"-",
"1.0",
",",
"uv",
".",
"y",
")",
"if",
"azimuth",
"<",
"0",
"return",
"Vector2",
".",
"new",
"(",
"azimuth",
"/",
"2.0",
"/",
"Math",
"::",
"PI",
"+",
"0.5",
",",
"uv",
".",
"y",
")",
"if",
"vector",
".",
"x",
".",
"zero?",
"&&",
"vector",
".",
"z",
".",
"zero?",
"uv",
".",
"clone",
"end"
] | Texture fixing helper. Spheres have some odd behaviours. | [
"Texture",
"fixing",
"helper",
".",
"Spheres",
"have",
"some",
"odd",
"behaviours",
"."
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L162-L166 | train |
jellymann/mittsu | lib/mittsu/renderers/opengl/textures/texture.rb | Mittsu.Texture.filter_fallback | def filter_fallback(filter)
if filter == NearestFilter || filter == NearestMipMapNearestFilter || f == NearestMipMapLinearFilter
GL_NEAREST
end
GL_LINEAR
end | ruby | def filter_fallback(filter)
if filter == NearestFilter || filter == NearestMipMapNearestFilter || f == NearestMipMapLinearFilter
GL_NEAREST
end
GL_LINEAR
end | [
"def",
"filter_fallback",
"(",
"filter",
")",
"if",
"filter",
"==",
"NearestFilter",
"||",
"filter",
"==",
"NearestMipMapNearestFilter",
"||",
"f",
"==",
"NearestMipMapLinearFilter",
"GL_NEAREST",
"end",
"GL_LINEAR",
"end"
] | Fallback filters for non-power-of-2 textures | [
"Fallback",
"filters",
"for",
"non",
"-",
"power",
"-",
"of",
"-",
"2",
"textures"
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/renderers/opengl/textures/texture.rb#L79-L85 | train |
jellymann/mittsu | lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb | Mittsu.ShadowMapPlugin.update_virtual_light | def update_virtual_light(light, cascade)
virtual_light = light.shadow_cascade_array[cascade]
virtual_light.position.copy(light.position)
virtual_light.target.position.copy(light.target.position)
virtual_light.look_at(virtual_light.target)
virtual_light.shadow_camera_visible = light.shadow_camera_visible
virtual_light.shadow_darkness = light.shadow_darkness
virtual_light.shadow_bias = light.shadow_cascade_bias[cascade]
near_z = light.shadow_cascade_near_z[cascade]
far_z = light.shadow_cascade_far_z[cascade]
points_frustum = virtual_light.points_frustum
points_frustum[0].z = near_z
points_frustum[1].z = near_z
points_frustum[2].z = near_z
points_frustum[3].z = near_z
points_frustum[4].z = far_z
points_frustum[5].z = far_z
points_frustum[6].z = far_z
points_frustum[7].z = far_z
end | ruby | def update_virtual_light(light, cascade)
virtual_light = light.shadow_cascade_array[cascade]
virtual_light.position.copy(light.position)
virtual_light.target.position.copy(light.target.position)
virtual_light.look_at(virtual_light.target)
virtual_light.shadow_camera_visible = light.shadow_camera_visible
virtual_light.shadow_darkness = light.shadow_darkness
virtual_light.shadow_bias = light.shadow_cascade_bias[cascade]
near_z = light.shadow_cascade_near_z[cascade]
far_z = light.shadow_cascade_far_z[cascade]
points_frustum = virtual_light.points_frustum
points_frustum[0].z = near_z
points_frustum[1].z = near_z
points_frustum[2].z = near_z
points_frustum[3].z = near_z
points_frustum[4].z = far_z
points_frustum[5].z = far_z
points_frustum[6].z = far_z
points_frustum[7].z = far_z
end | [
"def",
"update_virtual_light",
"(",
"light",
",",
"cascade",
")",
"virtual_light",
"=",
"light",
".",
"shadow_cascade_array",
"[",
"cascade",
"]",
"virtual_light",
".",
"position",
".",
"copy",
"(",
"light",
".",
"position",
")",
"virtual_light",
".",
"target",
".",
"position",
".",
"copy",
"(",
"light",
".",
"target",
".",
"position",
")",
"virtual_light",
".",
"look_at",
"(",
"virtual_light",
".",
"target",
")",
"virtual_light",
".",
"shadow_camera_visible",
"=",
"light",
".",
"shadow_camera_visible",
"virtual_light",
".",
"shadow_darkness",
"=",
"light",
".",
"shadow_darkness",
"virtual_light",
".",
"shadow_bias",
"=",
"light",
".",
"shadow_cascade_bias",
"[",
"cascade",
"]",
"near_z",
"=",
"light",
".",
"shadow_cascade_near_z",
"[",
"cascade",
"]",
"far_z",
"=",
"light",
".",
"shadow_cascade_far_z",
"[",
"cascade",
"]",
"points_frustum",
"=",
"virtual_light",
".",
"points_frustum",
"points_frustum",
"[",
"0",
"]",
".",
"z",
"=",
"near_z",
"points_frustum",
"[",
"1",
"]",
".",
"z",
"=",
"near_z",
"points_frustum",
"[",
"2",
"]",
".",
"z",
"=",
"near_z",
"points_frustum",
"[",
"3",
"]",
".",
"z",
"=",
"near_z",
"points_frustum",
"[",
"4",
"]",
".",
"z",
"=",
"far_z",
"points_frustum",
"[",
"5",
"]",
".",
"z",
"=",
"far_z",
"points_frustum",
"[",
"6",
"]",
".",
"z",
"=",
"far_z",
"points_frustum",
"[",
"7",
"]",
".",
"z",
"=",
"far_z",
"end"
] | synchronize virtual light with the original light | [
"synchronize",
"virtual",
"light",
"with",
"the",
"original",
"light"
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb#L338-L364 | train |
jellymann/mittsu | lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb | Mittsu.ShadowMapPlugin.update_shadow_camera | def update_shadow_camera(camera, light)
shadow_camera = light.shadow_camera
points_frustum = light.pointa_frustum
points_world = light.points_world
@min.set(Float::INFINITY, Float::INFINITY, Float::INFINITY)
@max.set(-Float::INFINITY, -Float::INFINITY, -Float::INFINITY)
8.times do |i|
p = points_world[i]
p.copy(points_frustum[i])
p.unproject(camera)
p.apply_matrix4(shadow_camera.matrix_world_inverse)
@min.x = p.x if (p.x < @min.x)
@max.x = p.x if (p.x > @max.x)
@min.y = p.y if (p.y < @min.y)
@max.y = p.y if (p.y > @max.y)
@min.z = p.z if (p.z < @min.z)
@max.z = p.z if (p.z > @max.z)
end
shadow_camera.left = @min.x
shadow_camera.right = @max.x
shadow_camera.top = @max.y
shadow_camera.bottom = @min.y
# can't really fit near/far
# shadow_camera.near = @min.x
# shadow_camera.far = @max.z
shadow_camera.update_projection_matrix
end | ruby | def update_shadow_camera(camera, light)
shadow_camera = light.shadow_camera
points_frustum = light.pointa_frustum
points_world = light.points_world
@min.set(Float::INFINITY, Float::INFINITY, Float::INFINITY)
@max.set(-Float::INFINITY, -Float::INFINITY, -Float::INFINITY)
8.times do |i|
p = points_world[i]
p.copy(points_frustum[i])
p.unproject(camera)
p.apply_matrix4(shadow_camera.matrix_world_inverse)
@min.x = p.x if (p.x < @min.x)
@max.x = p.x if (p.x > @max.x)
@min.y = p.y if (p.y < @min.y)
@max.y = p.y if (p.y > @max.y)
@min.z = p.z if (p.z < @min.z)
@max.z = p.z if (p.z > @max.z)
end
shadow_camera.left = @min.x
shadow_camera.right = @max.x
shadow_camera.top = @max.y
shadow_camera.bottom = @min.y
# can't really fit near/far
# shadow_camera.near = @min.x
# shadow_camera.far = @max.z
shadow_camera.update_projection_matrix
end | [
"def",
"update_shadow_camera",
"(",
"camera",
",",
"light",
")",
"shadow_camera",
"=",
"light",
".",
"shadow_camera",
"points_frustum",
"=",
"light",
".",
"pointa_frustum",
"points_world",
"=",
"light",
".",
"points_world",
"@min",
".",
"set",
"(",
"Float",
"::",
"INFINITY",
",",
"Float",
"::",
"INFINITY",
",",
"Float",
"::",
"INFINITY",
")",
"@max",
".",
"set",
"(",
"-",
"Float",
"::",
"INFINITY",
",",
"-",
"Float",
"::",
"INFINITY",
",",
"-",
"Float",
"::",
"INFINITY",
")",
"8",
".",
"times",
"do",
"|",
"i",
"|",
"p",
"=",
"points_world",
"[",
"i",
"]",
"p",
".",
"copy",
"(",
"points_frustum",
"[",
"i",
"]",
")",
"p",
".",
"unproject",
"(",
"camera",
")",
"p",
".",
"apply_matrix4",
"(",
"shadow_camera",
".",
"matrix_world_inverse",
")",
"@min",
".",
"x",
"=",
"p",
".",
"x",
"if",
"(",
"p",
".",
"x",
"<",
"@min",
".",
"x",
")",
"@max",
".",
"x",
"=",
"p",
".",
"x",
"if",
"(",
"p",
".",
"x",
">",
"@max",
".",
"x",
")",
"@min",
".",
"y",
"=",
"p",
".",
"y",
"if",
"(",
"p",
".",
"y",
"<",
"@min",
".",
"y",
")",
"@max",
".",
"y",
"=",
"p",
".",
"y",
"if",
"(",
"p",
".",
"y",
">",
"@max",
".",
"y",
")",
"@min",
".",
"z",
"=",
"p",
".",
"z",
"if",
"(",
"p",
".",
"z",
"<",
"@min",
".",
"z",
")",
"@max",
".",
"z",
"=",
"p",
".",
"z",
"if",
"(",
"p",
".",
"z",
">",
"@max",
".",
"z",
")",
"end",
"shadow_camera",
".",
"left",
"=",
"@min",
".",
"x",
"shadow_camera",
".",
"right",
"=",
"@max",
".",
"x",
"shadow_camera",
".",
"top",
"=",
"@max",
".",
"y",
"shadow_camera",
".",
"bottom",
"=",
"@min",
".",
"y",
"# can't really fit near/far",
"# shadow_camera.near = @min.x",
"# shadow_camera.far = @max.z",
"shadow_camera",
".",
"update_projection_matrix",
"end"
] | fit shadow camera's ortho frustum to camera frustum | [
"fit",
"shadow",
"camera",
"s",
"ortho",
"frustum",
"to",
"camera",
"frustum"
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb#L368-L404 | train |
jellymann/mittsu | lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb | Mittsu.ShadowMapPlugin.get_object_material | def get_object_material(object)
if object.material.is_a?(MeshFaceMaterial)
object.material.materials[0]
else
object.material
end
end | ruby | def get_object_material(object)
if object.material.is_a?(MeshFaceMaterial)
object.material.materials[0]
else
object.material
end
end | [
"def",
"get_object_material",
"(",
"object",
")",
"if",
"object",
".",
"material",
".",
"is_a?",
"(",
"MeshFaceMaterial",
")",
"object",
".",
"material",
".",
"materials",
"[",
"0",
"]",
"else",
"object",
".",
"material",
"end",
"end"
] | For the moment just ignore objects that have multiple materials with different animation methods
Only the frst material will be taken into account for deciding which depth material to use for shadow maps | [
"For",
"the",
"moment",
"just",
"ignore",
"objects",
"that",
"have",
"multiple",
"materials",
"with",
"different",
"animation",
"methods",
"Only",
"the",
"frst",
"material",
"will",
"be",
"taken",
"into",
"account",
"for",
"deciding",
"which",
"depth",
"material",
"to",
"use",
"for",
"shadow",
"maps"
] | 955bde855c727d775b80f2c88457cb4b58c8c8f8 | https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb#L409-L415 | train |
reinteractive/wallaby | lib/helpers/wallaby/resources_helper.rb | Wallaby.ResourcesHelper.show_title | def show_title(decorated)
raise ::ArgumentError unless decorated.is_a? ResourceDecorator
[
to_model_label(decorated.model_class), decorated.to_label
].compact.join ': '
end | ruby | def show_title(decorated)
raise ::ArgumentError unless decorated.is_a? ResourceDecorator
[
to_model_label(decorated.model_class), decorated.to_label
].compact.join ': '
end | [
"def",
"show_title",
"(",
"decorated",
")",
"raise",
"::",
"ArgumentError",
"unless",
"decorated",
".",
"is_a?",
"ResourceDecorator",
"[",
"to_model_label",
"(",
"decorated",
".",
"model_class",
")",
",",
"decorated",
".",
"to_label",
"]",
".",
"compact",
".",
"join",
"': '",
"end"
] | Title for show page of given resource
@param decorated [Wallaby::ResourceDecorator]
@return [String] | [
"Title",
"for",
"show",
"page",
"of",
"given",
"resource"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/resources_helper.rb#L31-L36 | train |
reinteractive/wallaby | lib/helpers/wallaby/secure_helper.rb | Wallaby.SecureHelper.user_portrait | def user_portrait(user = current_user)
email_method = security.email_method || :email
email = ModuleUtils.try_to user, email_method
if email.present?
https = "http#{request.ssl? ? 's' : EMPTY_STRING}"
email_md5 = ::Digest::MD5.hexdigest email.downcase
image_source = "#{https}://www.gravatar.com/avatar/#{email_md5}"
image_tag image_source, class: 'user'
else
fa_icon 'user'
end
end | ruby | def user_portrait(user = current_user)
email_method = security.email_method || :email
email = ModuleUtils.try_to user, email_method
if email.present?
https = "http#{request.ssl? ? 's' : EMPTY_STRING}"
email_md5 = ::Digest::MD5.hexdigest email.downcase
image_source = "#{https}://www.gravatar.com/avatar/#{email_md5}"
image_tag image_source, class: 'user'
else
fa_icon 'user'
end
end | [
"def",
"user_portrait",
"(",
"user",
"=",
"current_user",
")",
"email_method",
"=",
"security",
".",
"email_method",
"||",
":email",
"email",
"=",
"ModuleUtils",
".",
"try_to",
"user",
",",
"email_method",
"if",
"email",
".",
"present?",
"https",
"=",
"\"http#{request.ssl? ? 's' : EMPTY_STRING}\"",
"email_md5",
"=",
"::",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"email",
".",
"downcase",
"image_source",
"=",
"\"#{https}://www.gravatar.com/avatar/#{email_md5}\"",
"image_tag",
"image_source",
",",
"class",
":",
"'user'",
"else",
"fa_icon",
"'user'",
"end",
"end"
] | Image portrait for given user.
- if email is present, a gravatar image tag will be returned
- otherwise, an user icon will be returned
@param user [Object]
@return [String] IMG or I element | [
"Image",
"portrait",
"for",
"given",
"user",
".",
"-",
"if",
"email",
"is",
"present",
"a",
"gravatar",
"image",
"tag",
"will",
"be",
"returned",
"-",
"otherwise",
"an",
"user",
"icon",
"will",
"be",
"returned"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/secure_helper.rb#L9-L20 | train |
reinteractive/wallaby | lib/helpers/wallaby/secure_helper.rb | Wallaby.SecureHelper.logout_path | def logout_path(user = current_user, app = main_app)
path = security.logout_path
path ||=
if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
"destroy_#{scope}_session_path"
end
ModuleUtils.try_to app, path
end | ruby | def logout_path(user = current_user, app = main_app)
path = security.logout_path
path ||=
if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
"destroy_#{scope}_session_path"
end
ModuleUtils.try_to app, path
end | [
"def",
"logout_path",
"(",
"user",
"=",
"current_user",
",",
"app",
"=",
"main_app",
")",
"path",
"=",
"security",
".",
"logout_path",
"path",
"||=",
"if",
"defined?",
"::",
"Devise",
"scope",
"=",
"::",
"Devise",
"::",
"Mapping",
".",
"find_scope!",
"user",
"\"destroy_#{scope}_session_path\"",
"end",
"ModuleUtils",
".",
"try_to",
"app",
",",
"path",
"end"
] | Logout path for given user
@see Wallaby::Configuration::Security#logout_path
@param user [Object]
@param app [Object]
@return [String] URL to log out | [
"Logout",
"path",
"for",
"given",
"user"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/secure_helper.rb#L27-L35 | train |
reinteractive/wallaby | lib/helpers/wallaby/secure_helper.rb | Wallaby.SecureHelper.logout_method | def logout_method(user = current_user)
http_method = security.logout_method
http_method || if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
mapping = ::Devise.mappings[scope]
mapping.sign_out_via
end
end | ruby | def logout_method(user = current_user)
http_method = security.logout_method
http_method || if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
mapping = ::Devise.mappings[scope]
mapping.sign_out_via
end
end | [
"def",
"logout_method",
"(",
"user",
"=",
"current_user",
")",
"http_method",
"=",
"security",
".",
"logout_method",
"http_method",
"||",
"if",
"defined?",
"::",
"Devise",
"scope",
"=",
"::",
"Devise",
"::",
"Mapping",
".",
"find_scope!",
"user",
"mapping",
"=",
"::",
"Devise",
".",
"mappings",
"[",
"scope",
"]",
"mapping",
".",
"sign_out_via",
"end",
"end"
] | Logout method for given user
@see Wallaby::Configuration::Security#logout_method
@param user [Object]
@return [String, Symbol] http method to log out | [
"Logout",
"method",
"for",
"given",
"user"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/secure_helper.rb#L41-L48 | train |
reinteractive/wallaby | lib/routes/wallaby/resources_router.rb | Wallaby.ResourcesRouter.find_controller_by | def find_controller_by(params)
model_class = find_model_class_by params
Map.controller_map(model_class, params[:resources_controller]) || default_controller(params)
end | ruby | def find_controller_by(params)
model_class = find_model_class_by params
Map.controller_map(model_class, params[:resources_controller]) || default_controller(params)
end | [
"def",
"find_controller_by",
"(",
"params",
")",
"model_class",
"=",
"find_model_class_by",
"params",
"Map",
".",
"controller_map",
"(",
"model_class",
",",
"params",
"[",
":resources_controller",
"]",
")",
"||",
"default_controller",
"(",
"params",
")",
"end"
] | Find controller class
@param params [Hash]
@return [Class] controller class | [
"Find",
"controller",
"class"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/routes/wallaby/resources_router.rb#L29-L32 | train |
reinteractive/wallaby | lib/routes/wallaby/resources_router.rb | Wallaby.ResourcesRouter.find_model_class_by | def find_model_class_by(params)
model_class = Map.model_class_map params[:resources]
return model_class unless MODEL_ACTIONS.include? params[:action].to_sym
raise ModelNotFound, params[:resources] unless model_class
unless Map.mode_map[model_class]
raise UnprocessableEntity, I18n.t('errors.unprocessable_entity.model', model: model_class)
end
model_class
end | ruby | def find_model_class_by(params)
model_class = Map.model_class_map params[:resources]
return model_class unless MODEL_ACTIONS.include? params[:action].to_sym
raise ModelNotFound, params[:resources] unless model_class
unless Map.mode_map[model_class]
raise UnprocessableEntity, I18n.t('errors.unprocessable_entity.model', model: model_class)
end
model_class
end | [
"def",
"find_model_class_by",
"(",
"params",
")",
"model_class",
"=",
"Map",
".",
"model_class_map",
"params",
"[",
":resources",
"]",
"return",
"model_class",
"unless",
"MODEL_ACTIONS",
".",
"include?",
"params",
"[",
":action",
"]",
".",
"to_sym",
"raise",
"ModelNotFound",
",",
"params",
"[",
":resources",
"]",
"unless",
"model_class",
"unless",
"Map",
".",
"mode_map",
"[",
"model_class",
"]",
"raise",
"UnprocessableEntity",
",",
"I18n",
".",
"t",
"(",
"'errors.unprocessable_entity.model'",
",",
"model",
":",
"model_class",
")",
"end",
"model_class",
"end"
] | Find out the model class
@param params [Hash]
@return [Class]
@raise [Wallaby::ModelNotFound] when model class is not found
@raise [Wallaby::UnprocessableEntity] when there is no corresponding mode found for model class | [
"Find",
"out",
"the",
"model",
"class"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/routes/wallaby/resources_router.rb#L49-L57 | train |
reinteractive/wallaby | lib/routes/wallaby/resources_router.rb | Wallaby.ResourcesRouter.set_message_for | def set_message_for(exception, env)
session = env[ActionDispatch::Request::Session::ENV_SESSION_KEY] || {}
env[ActionDispatch::Flash::KEY] ||= ActionDispatch::Flash::FlashHash.from_session_value session['flash']
flash = env[ActionDispatch::Flash::KEY]
flash[:alert] = exception.message
end | ruby | def set_message_for(exception, env)
session = env[ActionDispatch::Request::Session::ENV_SESSION_KEY] || {}
env[ActionDispatch::Flash::KEY] ||= ActionDispatch::Flash::FlashHash.from_session_value session['flash']
flash = env[ActionDispatch::Flash::KEY]
flash[:alert] = exception.message
end | [
"def",
"set_message_for",
"(",
"exception",
",",
"env",
")",
"session",
"=",
"env",
"[",
"ActionDispatch",
"::",
"Request",
"::",
"Session",
"::",
"ENV_SESSION_KEY",
"]",
"||",
"{",
"}",
"env",
"[",
"ActionDispatch",
"::",
"Flash",
"::",
"KEY",
"]",
"||=",
"ActionDispatch",
"::",
"Flash",
"::",
"FlashHash",
".",
"from_session_value",
"session",
"[",
"'flash'",
"]",
"flash",
"=",
"env",
"[",
"ActionDispatch",
"::",
"Flash",
"::",
"KEY",
"]",
"flash",
"[",
":alert",
"]",
"=",
"exception",
".",
"message",
"end"
] | Set flash error message
@param exception [Exception]
@param env [Hash] @see http://www.rubydoc.info/github/rack/rack/master/file/SPEC | [
"Set",
"flash",
"error",
"message"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/routes/wallaby/resources_router.rb#L62-L67 | train |
reinteractive/wallaby | lib/interfaces/wallaby/model_decorator.rb | Wallaby.ModelDecorator.validate_presence_of | def validate_presence_of(field_name, type)
type || raise(::ArgumentError, I18n.t('errors.invalid.type_required', field_name: field_name))
end | ruby | def validate_presence_of(field_name, type)
type || raise(::ArgumentError, I18n.t('errors.invalid.type_required', field_name: field_name))
end | [
"def",
"validate_presence_of",
"(",
"field_name",
",",
"type",
")",
"type",
"||",
"raise",
"(",
"::",
"ArgumentError",
",",
"I18n",
".",
"t",
"(",
"'errors.invalid.type_required'",
",",
"field_name",
":",
"field_name",
")",
")",
"end"
] | Validate presence of a type for given field name
@param type [String, Symbol, nil]
@return [String, Symbol] type
@raise [ArgumentError] when type is nil | [
"Validate",
"presence",
"of",
"a",
"type",
"for",
"given",
"field",
"name"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/interfaces/wallaby/model_decorator.rb#L158-L160 | train |
reinteractive/wallaby | lib/helpers/wallaby/styling_helper.rb | Wallaby.StylingHelper.itooltip | def itooltip(title, icon_suffix = 'info-circle', html_options = {})
html_options[:title] = title
(html_options[:data] ||= {}).merge! toggle: 'tooltip', placement: 'top'
fa_icon icon_suffix, html_options
end | ruby | def itooltip(title, icon_suffix = 'info-circle', html_options = {})
html_options[:title] = title
(html_options[:data] ||= {}).merge! toggle: 'tooltip', placement: 'top'
fa_icon icon_suffix, html_options
end | [
"def",
"itooltip",
"(",
"title",
",",
"icon_suffix",
"=",
"'info-circle'",
",",
"html_options",
"=",
"{",
"}",
")",
"html_options",
"[",
":title",
"]",
"=",
"title",
"(",
"html_options",
"[",
":data",
"]",
"||=",
"{",
"}",
")",
".",
"merge!",
"toggle",
":",
"'tooltip'",
",",
"placement",
":",
"'top'",
"fa_icon",
"icon_suffix",
",",
"html_options",
"end"
] | Build up tooltip
@param title [String]
@param icon_suffix [String]
@param html_options [Hash]
@return [String] tooltip HTML | [
"Build",
"up",
"tooltip"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/styling_helper.rb#L31-L36 | train |
reinteractive/wallaby | lib/helpers/wallaby/styling_helper.rb | Wallaby.StylingHelper.imodal | def imodal(title, body, html_options = {})
label ||= html_options.delete(:label) \
|| html_options.delete(:icon) || fa_icon('clone')
content_tag :span, class: 'modaler' do
concat link_to(label, '#', data: { target: '#imodal', toggle: 'modal' })
concat content_tag(:span, title, class: 'modaler__title')
concat content_tag(:span, body, class: 'modaler__body')
end
end | ruby | def imodal(title, body, html_options = {})
label ||= html_options.delete(:label) \
|| html_options.delete(:icon) || fa_icon('clone')
content_tag :span, class: 'modaler' do
concat link_to(label, '#', data: { target: '#imodal', toggle: 'modal' })
concat content_tag(:span, title, class: 'modaler__title')
concat content_tag(:span, body, class: 'modaler__body')
end
end | [
"def",
"imodal",
"(",
"title",
",",
"body",
",",
"html_options",
"=",
"{",
"}",
")",
"label",
"||=",
"html_options",
".",
"delete",
"(",
":label",
")",
"||",
"html_options",
".",
"delete",
"(",
":icon",
")",
"||",
"fa_icon",
"(",
"'clone'",
")",
"content_tag",
":span",
",",
"class",
":",
"'modaler'",
"do",
"concat",
"link_to",
"(",
"label",
",",
"'#'",
",",
"data",
":",
"{",
"target",
":",
"'#imodal'",
",",
"toggle",
":",
"'modal'",
"}",
")",
"concat",
"content_tag",
"(",
":span",
",",
"title",
",",
"class",
":",
"'modaler__title'",
")",
"concat",
"content_tag",
"(",
":span",
",",
"body",
",",
"class",
":",
"'modaler__body'",
")",
"end",
"end"
] | Build up modal
@param title [String]
@param body [String]
@param html_options [Hash]
@return [String] modal HTML | [
"Build",
"up",
"modal"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/styling_helper.rb#L43-L51 | train |
reinteractive/wallaby | lib/forms/wallaby/form_builder.rb | Wallaby.FormBuilder.error_messages | def error_messages(field_name)
errors = Array object.errors[field_name]
return if errors.blank?
content_tag :ul, class: 'errors' do
errors.each do |message|
concat content_tag :li, content_tag(:small, raw(message))
end
end
end | ruby | def error_messages(field_name)
errors = Array object.errors[field_name]
return if errors.blank?
content_tag :ul, class: 'errors' do
errors.each do |message|
concat content_tag :li, content_tag(:small, raw(message))
end
end
end | [
"def",
"error_messages",
"(",
"field_name",
")",
"errors",
"=",
"Array",
"object",
".",
"errors",
"[",
"field_name",
"]",
"return",
"if",
"errors",
".",
"blank?",
"content_tag",
":ul",
",",
"class",
":",
"'errors'",
"do",
"errors",
".",
"each",
"do",
"|",
"message",
"|",
"concat",
"content_tag",
":li",
",",
"content_tag",
"(",
":small",
",",
"raw",
"(",
"message",
")",
")",
"end",
"end",
"end"
] | Build up the HTML for displaying error messages
@param field_name [String/Symbol]
@return [String] HTML | [
"Build",
"up",
"the",
"HTML",
"for",
"displaying",
"error",
"messages"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/forms/wallaby/form_builder.rb#L14-L23 | train |
reinteractive/wallaby | lib/forms/wallaby/form_builder.rb | Wallaby.FormBuilder.label | def label(method, text = nil, options = {}, &block)
text = instance_exec(&text) if text.is_a?(Proc)
super
end | ruby | def label(method, text = nil, options = {}, &block)
text = instance_exec(&text) if text.is_a?(Proc)
super
end | [
"def",
"label",
"(",
"method",
",",
"text",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"text",
"=",
"instance_exec",
"(",
"text",
")",
"if",
"text",
".",
"is_a?",
"(",
"Proc",
")",
"super",
"end"
] | Extend label to accept proc type `text` argument
@see ActionView::Helpers::FormBuilder#label | [
"Extend",
"label",
"to",
"accept",
"proc",
"type",
"text",
"argument"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/forms/wallaby/form_builder.rb#L27-L30 | train |
reinteractive/wallaby | lib/forms/wallaby/form_builder.rb | Wallaby.FormBuilder.select | def select(method, choices = nil, options = {}, html_options = {}, &block)
choices = instance_exec(&choices) if choices.is_a?(Proc)
super
end | ruby | def select(method, choices = nil, options = {}, html_options = {}, &block)
choices = instance_exec(&choices) if choices.is_a?(Proc)
super
end | [
"def",
"select",
"(",
"method",
",",
"choices",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"choices",
"=",
"instance_exec",
"(",
"choices",
")",
"if",
"choices",
".",
"is_a?",
"(",
"Proc",
")",
"super",
"end"
] | Extend select to accept proc type `choices` argument
@see ActionView::Helpers::FormBuilder#select | [
"Extend",
"select",
"to",
"accept",
"proc",
"type",
"choices",
"argument"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/forms/wallaby/form_builder.rb#L34-L37 | train |
reinteractive/wallaby | lib/forms/wallaby/form_builder.rb | Wallaby.FormBuilder.method_missing | def method_missing(method, *args, &block)
return super unless @template.respond_to? method
# Delegate the method so that we don't come in here the next time
# when same method is called
self.class.delegate method, to: :@template
@template.public_send method, *args, &block
end | ruby | def method_missing(method, *args, &block)
return super unless @template.respond_to? method
# Delegate the method so that we don't come in here the next time
# when same method is called
self.class.delegate method, to: :@template
@template.public_send method, *args, &block
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"super",
"unless",
"@template",
".",
"respond_to?",
"method",
"# Delegate the method so that we don't come in here the next time",
"# when same method is called",
"self",
".",
"class",
".",
"delegate",
"method",
",",
"to",
":",
":@template",
"@template",
".",
"public_send",
"method",
",",
"args",
",",
"block",
"end"
] | Delegate missing method to `@template` | [
"Delegate",
"missing",
"method",
"to"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/forms/wallaby/form_builder.rb#L42-L48 | train |
reinteractive/wallaby | lib/helpers/wallaby/form_helper.rb | Wallaby.FormHelper.remote_url | def remote_url(url, model_class, wildcard = 'QUERY')
url || index_path(model_class, url_params: { q: wildcard, per: pagination.page_size })
end | ruby | def remote_url(url, model_class, wildcard = 'QUERY')
url || index_path(model_class, url_params: { q: wildcard, per: pagination.page_size })
end | [
"def",
"remote_url",
"(",
"url",
",",
"model_class",
",",
"wildcard",
"=",
"'QUERY'",
")",
"url",
"||",
"index_path",
"(",
"model_class",
",",
"url_params",
":",
"{",
"q",
":",
"wildcard",
",",
"per",
":",
"pagination",
".",
"page_size",
"}",
")",
"end"
] | To generate remote URL for auto select plugin.
@see https://github.com/reinteractive/wallaby/blob/master/app/assets/javascripts/wallaby/auto_select.js
auto_select.js
@param url [String, nil]
if URL is nil, it will fall back to default remote URL
@param model_class [Class]
@param wildcard [String] wildcard that auto_select uses to replace with
the typed keyword
@return [String] URL for autocomplete | [
"To",
"generate",
"remote",
"URL",
"for",
"auto",
"select",
"plugin",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/form_helper.rb#L19-L21 | train |
reinteractive/wallaby | lib/helpers/wallaby/index_helper.rb | Wallaby.IndexHelper.filter_link | def filter_link(model_class, filter_name, filters: {}, url_params: {})
is_all = filter_name == :all
config = filters[filter_name] || {}
label = is_all ? all_label : filter_label(filter_name, filters)
url_params =
if config[:default] then index_params.except(:filter).merge(url_params)
else index_params.merge(filter: filter_name).merge(url_params)
end
index_link(model_class, url_params: url_params) { label }
end | ruby | def filter_link(model_class, filter_name, filters: {}, url_params: {})
is_all = filter_name == :all
config = filters[filter_name] || {}
label = is_all ? all_label : filter_label(filter_name, filters)
url_params =
if config[:default] then index_params.except(:filter).merge(url_params)
else index_params.merge(filter: filter_name).merge(url_params)
end
index_link(model_class, url_params: url_params) { label }
end | [
"def",
"filter_link",
"(",
"model_class",
",",
"filter_name",
",",
"filters",
":",
"{",
"}",
",",
"url_params",
":",
"{",
"}",
")",
"is_all",
"=",
"filter_name",
"==",
":all",
"config",
"=",
"filters",
"[",
"filter_name",
"]",
"||",
"{",
"}",
"label",
"=",
"is_all",
"?",
"all_label",
":",
"filter_label",
"(",
"filter_name",
",",
"filters",
")",
"url_params",
"=",
"if",
"config",
"[",
":default",
"]",
"then",
"index_params",
".",
"except",
"(",
":filter",
")",
".",
"merge",
"(",
"url_params",
")",
"else",
"index_params",
".",
"merge",
"(",
"filter",
":",
"filter_name",
")",
".",
"merge",
"(",
"url_params",
")",
"end",
"index_link",
"(",
"model_class",
",",
"url_params",
":",
"url_params",
")",
"{",
"label",
"}",
"end"
] | Link for a given model class and filter name
@param model_class [Class]
@param filter_name [String, Symbol]
@param filters [Hash]
@param url_params [Hash, ActionController::Parameters]
@return [String] HTML anchor link | [
"Link",
"for",
"a",
"given",
"model",
"class",
"and",
"filter",
"name"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/index_helper.rb#L54-L63 | train |
reinteractive/wallaby | lib/helpers/wallaby/index_helper.rb | Wallaby.IndexHelper.export_link | def export_link(model_class, url_params: {})
url_params = index_params.except(:page, :per).merge(format: 'csv').merge(url_params)
index_link(model_class, url_params: url_params) { t 'links.export', ext: 'CSV' }
end | ruby | def export_link(model_class, url_params: {})
url_params = index_params.except(:page, :per).merge(format: 'csv').merge(url_params)
index_link(model_class, url_params: url_params) { t 'links.export', ext: 'CSV' }
end | [
"def",
"export_link",
"(",
"model_class",
",",
"url_params",
":",
"{",
"}",
")",
"url_params",
"=",
"index_params",
".",
"except",
"(",
":page",
",",
":per",
")",
".",
"merge",
"(",
"format",
":",
"'csv'",
")",
".",
"merge",
"(",
"url_params",
")",
"index_link",
"(",
"model_class",
",",
"url_params",
":",
"url_params",
")",
"{",
"t",
"'links.export'",
",",
"ext",
":",
"'CSV'",
"}",
"end"
] | Export link for a given model_class.
It accepts extra url params
@param model_class [Class]
@param url_params [Hash, ActionController::Parameters] extra URL params
@return [String] HTML anchor link | [
"Export",
"link",
"for",
"a",
"given",
"model_class",
".",
"It",
"accepts",
"extra",
"url",
"params"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/index_helper.rb#L70-L73 | train |
reinteractive/wallaby | lib/helpers/wallaby/base_helper.rb | Wallaby.BaseHelper.model_classes | def model_classes(classes = Map.model_classes)
nested_hash = classes.each_with_object({}) do |klass, hash|
hash[klass] = Node.new(klass)
end
nested_hash.each do |klass, node|
node.parent = parent = nested_hash[klass.superclass]
parent.children << node if parent
end
nested_hash.values.select { |v| v.parent.nil? }
end | ruby | def model_classes(classes = Map.model_classes)
nested_hash = classes.each_with_object({}) do |klass, hash|
hash[klass] = Node.new(klass)
end
nested_hash.each do |klass, node|
node.parent = parent = nested_hash[klass.superclass]
parent.children << node if parent
end
nested_hash.values.select { |v| v.parent.nil? }
end | [
"def",
"model_classes",
"(",
"classes",
"=",
"Map",
".",
"model_classes",
")",
"nested_hash",
"=",
"classes",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"klass",
",",
"hash",
"|",
"hash",
"[",
"klass",
"]",
"=",
"Node",
".",
"new",
"(",
"klass",
")",
"end",
"nested_hash",
".",
"each",
"do",
"|",
"klass",
",",
"node",
"|",
"node",
".",
"parent",
"=",
"parent",
"=",
"nested_hash",
"[",
"klass",
".",
"superclass",
"]",
"parent",
".",
"children",
"<<",
"node",
"if",
"parent",
"end",
"nested_hash",
".",
"values",
".",
"select",
"{",
"|",
"v",
"|",
"v",
".",
"parent",
".",
"nil?",
"}",
"end"
] | Turn a list of classes into tree structure by inheritance.
@param classes [Array<Class>]
a list of all the classes that wallaby supports
@return [Array<Wallaby::Node>] a tree structure of given classes | [
"Turn",
"a",
"list",
"of",
"classes",
"into",
"tree",
"structure",
"by",
"inheritance",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/base_helper.rb#L36-L45 | train |
reinteractive/wallaby | lib/helpers/wallaby/base_helper.rb | Wallaby.BaseHelper.model_tree | def model_tree(array, base_class = nil)
return EMPTY_STRING.html_safe if array.blank?
options = { html_options: { class: 'dropdown-item' } }
content_tag :ul, class: 'dropdown-menu', 'aria-labelledby': base_class do
array.sort_by(&:name).each do |node|
content = index_link(node.klass, options).try :<<, model_tree(node.children)
concat content_tag(:li, content)
end
end
end | ruby | def model_tree(array, base_class = nil)
return EMPTY_STRING.html_safe if array.blank?
options = { html_options: { class: 'dropdown-item' } }
content_tag :ul, class: 'dropdown-menu', 'aria-labelledby': base_class do
array.sort_by(&:name).each do |node|
content = index_link(node.klass, options).try :<<, model_tree(node.children)
concat content_tag(:li, content)
end
end
end | [
"def",
"model_tree",
"(",
"array",
",",
"base_class",
"=",
"nil",
")",
"return",
"EMPTY_STRING",
".",
"html_safe",
"if",
"array",
".",
"blank?",
"options",
"=",
"{",
"html_options",
":",
"{",
"class",
":",
"'dropdown-item'",
"}",
"}",
"content_tag",
":ul",
",",
"class",
":",
"'dropdown-menu'",
",",
"'aria-labelledby'",
":",
"base_class",
"do",
"array",
".",
"sort_by",
"(",
":name",
")",
".",
"each",
"do",
"|",
"node",
"|",
"content",
"=",
"index_link",
"(",
"node",
".",
"klass",
",",
"options",
")",
".",
"try",
":<<",
",",
"model_tree",
"(",
"node",
".",
"children",
")",
"concat",
"content_tag",
"(",
":li",
",",
"content",
")",
"end",
"end",
"end"
] | Turn the tree of classes into a nested `ul` list.
@param array [Array<Wallaby::Node>] root classes
@return [String] HTML for the whole tree | [
"Turn",
"the",
"tree",
"of",
"classes",
"into",
"a",
"nested",
"ul",
"list",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/base_helper.rb#L50-L59 | train |
reinteractive/wallaby | lib/authorizers/wallaby/model_authorizer.rb | Wallaby.ModelAuthorizer.init_provider | def init_provider(context)
providers = Map.authorizer_provider_map model_class
provider_class = providers[self.class.provider_name]
provider_class ||= providers.values.find { |klass| klass.available? context }
provider_class.new context
end | ruby | def init_provider(context)
providers = Map.authorizer_provider_map model_class
provider_class = providers[self.class.provider_name]
provider_class ||= providers.values.find { |klass| klass.available? context }
provider_class.new context
end | [
"def",
"init_provider",
"(",
"context",
")",
"providers",
"=",
"Map",
".",
"authorizer_provider_map",
"model_class",
"provider_class",
"=",
"providers",
"[",
"self",
".",
"class",
".",
"provider_name",
"]",
"provider_class",
"||=",
"providers",
".",
"values",
".",
"find",
"{",
"|",
"klass",
"|",
"klass",
".",
"available?",
"context",
"}",
"provider_class",
".",
"new",
"context",
"end"
] | Go through provider list and detect which provider is used.
@param context [ActionController::Base]
@return [Wallaby::Authorizer] | [
"Go",
"through",
"provider",
"list",
"and",
"detect",
"which",
"provider",
"is",
"used",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/model_authorizer.rb#L69-L74 | train |
reinteractive/wallaby | app/controllers/wallaby/application_controller.rb | Wallaby.ApplicationController.error_rendering | def error_rendering(exception, symbol)
Rails.logger.error exception
@exception = exception
@symbol = symbol
@code = Rack::Utils::SYMBOL_TO_STATUS_CODE[symbol].to_i
respond_with @exception, status: @code, template: ERROR_PATH, prefixes: _prefixes
end | ruby | def error_rendering(exception, symbol)
Rails.logger.error exception
@exception = exception
@symbol = symbol
@code = Rack::Utils::SYMBOL_TO_STATUS_CODE[symbol].to_i
respond_with @exception, status: @code, template: ERROR_PATH, prefixes: _prefixes
end | [
"def",
"error_rendering",
"(",
"exception",
",",
"symbol",
")",
"Rails",
".",
"logger",
".",
"error",
"exception",
"@exception",
"=",
"exception",
"@symbol",
"=",
"symbol",
"@code",
"=",
"Rack",
"::",
"Utils",
"::",
"SYMBOL_TO_STATUS_CODE",
"[",
"symbol",
"]",
".",
"to_i",
"respond_with",
"@exception",
",",
"status",
":",
"@code",
",",
"template",
":",
"ERROR_PATH",
",",
"prefixes",
":",
"_prefixes",
"end"
] | Capture exceptions and display the error using error template.
@param exception [Exception]
@param symbol [Symbol] http status symbol | [
"Capture",
"exceptions",
"and",
"display",
"the",
"error",
"using",
"error",
"template",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/app/controllers/wallaby/application_controller.rb#L73-L80 | train |
reinteractive/wallaby | lib/concerns/wallaby/authorizable.rb | Wallaby.Authorizable.authorized? | def authorized?(action, subject)
return false unless subject
klass = subject.is_a?(Class) ? subject : subject.class
authorizer_of(klass).authorized? action, subject
end | ruby | def authorized?(action, subject)
return false unless subject
klass = subject.is_a?(Class) ? subject : subject.class
authorizer_of(klass).authorized? action, subject
end | [
"def",
"authorized?",
"(",
"action",
",",
"subject",
")",
"return",
"false",
"unless",
"subject",
"klass",
"=",
"subject",
".",
"is_a?",
"(",
"Class",
")",
"?",
"subject",
":",
"subject",
".",
"class",
"authorizer_of",
"(",
"klass",
")",
".",
"authorized?",
"action",
",",
"subject",
"end"
] | Check if user is allowed to perform action on given subject
@param action [Symbol, String]
@param subject [Object, Class]
@return [true] if allowed
@return [false] if not allowed
@since 5.2.0 | [
"Check",
"if",
"user",
"is",
"allowed",
"to",
"perform",
"action",
"on",
"given",
"subject"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/concerns/wallaby/authorizable.rb#L67-L71 | train |
reinteractive/wallaby | lib/concerns/wallaby/shared_helpers.rb | Wallaby.SharedHelpers.controller_to_get | def controller_to_get(attribute_name, class_attribute_name = nil)
class_attribute_name ||= attribute_name
return ModuleUtils.try_to self.class, class_attribute_name if is_a? ::ActionController::Base # controller?
ModuleUtils.try_to controller, attribute_name # view?
end | ruby | def controller_to_get(attribute_name, class_attribute_name = nil)
class_attribute_name ||= attribute_name
return ModuleUtils.try_to self.class, class_attribute_name if is_a? ::ActionController::Base # controller?
ModuleUtils.try_to controller, attribute_name # view?
end | [
"def",
"controller_to_get",
"(",
"attribute_name",
",",
"class_attribute_name",
"=",
"nil",
")",
"class_attribute_name",
"||=",
"attribute_name",
"return",
"ModuleUtils",
".",
"try_to",
"self",
".",
"class",
",",
"class_attribute_name",
"if",
"is_a?",
"::",
"ActionController",
"::",
"Base",
"# controller?",
"ModuleUtils",
".",
"try_to",
"controller",
",",
"attribute_name",
"# view?",
"end"
] | Fetch value for given attribute.
If it's used in controller, it will fetch it from class attribute.
If it's used in view, it will fetch it from controller.
@param attribute_name [String, Symbol] instance attribute name
@param class_attribute_name [String, Symbol] class attribute name
@return [Object] the value | [
"Fetch",
"value",
"for",
"given",
"attribute",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/concerns/wallaby/shared_helpers.rb#L13-L17 | train |
reinteractive/wallaby | lib/renderers/wallaby/custom_lookup_context.rb | Wallaby.CustomLookupContext.find_template | def find_template(name, prefixes = [], partial = false, keys = [], options = {})
prefixes = [] if partial && name.include?(SLASH) # reset the prefixes if `/` is detected
key = [name, prefixes, partial, keys, options].map(&:inspect).join(SLASH)
cached_lookup[key] ||= super
end | ruby | def find_template(name, prefixes = [], partial = false, keys = [], options = {})
prefixes = [] if partial && name.include?(SLASH) # reset the prefixes if `/` is detected
key = [name, prefixes, partial, keys, options].map(&:inspect).join(SLASH)
cached_lookup[key] ||= super
end | [
"def",
"find_template",
"(",
"name",
",",
"prefixes",
"=",
"[",
"]",
",",
"partial",
"=",
"false",
",",
"keys",
"=",
"[",
"]",
",",
"options",
"=",
"{",
"}",
")",
"prefixes",
"=",
"[",
"]",
"if",
"partial",
"&&",
"name",
".",
"include?",
"(",
"SLASH",
")",
"# reset the prefixes if `/` is detected",
"key",
"=",
"[",
"name",
",",
"prefixes",
",",
"partial",
",",
"keys",
",",
"options",
"]",
".",
"map",
"(",
":inspect",
")",
".",
"join",
"(",
"SLASH",
")",
"cached_lookup",
"[",
"key",
"]",
"||=",
"super",
"end"
] | It overrides the oirgin method to call the origin `find_template` and cache the result during a request.
@param name [String]
@param prefixes [Array<String>]
@param partial [Boolean]
@param keys [Array<String>] keys of local variables
@param options [Hash] | [
"It",
"overrides",
"the",
"oirgin",
"method",
"to",
"call",
"the",
"origin",
"find_template",
"and",
"cache",
"the",
"result",
"during",
"a",
"request",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/renderers/wallaby/custom_lookup_context.rb#L16-L20 | train |
reinteractive/wallaby | lib/authorizers/wallaby/pundit_authorization_provider.rb | Wallaby.PunditAuthorizationProvider.authorize | def authorize(action, subject)
context.send(:authorize, subject, normalize(action)) && subject
rescue ::Pundit::NotAuthorizedError
Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
raise Forbidden
end | ruby | def authorize(action, subject)
context.send(:authorize, subject, normalize(action)) && subject
rescue ::Pundit::NotAuthorizedError
Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
raise Forbidden
end | [
"def",
"authorize",
"(",
"action",
",",
"subject",
")",
"context",
".",
"send",
"(",
":authorize",
",",
"subject",
",",
"normalize",
"(",
"action",
")",
")",
"&&",
"subject",
"rescue",
"::",
"Pundit",
"::",
"NotAuthorizedError",
"Rails",
".",
"logger",
".",
"info",
"I18n",
".",
"t",
"(",
"'errors.unauthorized'",
",",
"user",
":",
"user",
",",
"action",
":",
"action",
",",
"subject",
":",
"subject",
")",
"raise",
"Forbidden",
"end"
] | Check user's permission for an action on given subject.
This method will be used in controller.
@param action [Symbol, String]
@param subject [Object, Class]
@raise [Wallaby::Forbidden] when user is not authorized to perform the action. | [
"Check",
"user",
"s",
"permission",
"for",
"an",
"action",
"on",
"given",
"subject",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/pundit_authorization_provider.rb#L18-L23 | train |
reinteractive/wallaby | lib/authorizers/wallaby/pundit_authorization_provider.rb | Wallaby.PunditAuthorizationProvider.authorized? | def authorized?(action, subject)
policy = context.send :policy, subject
ModuleUtils.try_to policy, normalize(action)
end | ruby | def authorized?(action, subject)
policy = context.send :policy, subject
ModuleUtils.try_to policy, normalize(action)
end | [
"def",
"authorized?",
"(",
"action",
",",
"subject",
")",
"policy",
"=",
"context",
".",
"send",
":policy",
",",
"subject",
"ModuleUtils",
".",
"try_to",
"policy",
",",
"normalize",
"(",
"action",
")",
"end"
] | Check and see if user is allowed to perform an action on given subject
@param action [Symbol, String]
@param subject [Object, Class]
@return [Boolean] | [
"Check",
"and",
"see",
"if",
"user",
"is",
"allowed",
"to",
"perform",
"an",
"action",
"on",
"given",
"subject"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/pundit_authorization_provider.rb#L29-L32 | train |
reinteractive/wallaby | lib/authorizers/wallaby/pundit_authorization_provider.rb | Wallaby.PunditAuthorizationProvider.attributes_for | def attributes_for(action, subject)
policy = context.send :policy, subject
value = ModuleUtils.try_to(policy, "attributes_for_#{action}") || ModuleUtils.try_to(policy, 'attributes_for')
Rails.logger.warn I18n.t('error.pundit.not_found.attributes_for', subject: subject) unless value
value || {}
end | ruby | def attributes_for(action, subject)
policy = context.send :policy, subject
value = ModuleUtils.try_to(policy, "attributes_for_#{action}") || ModuleUtils.try_to(policy, 'attributes_for')
Rails.logger.warn I18n.t('error.pundit.not_found.attributes_for', subject: subject) unless value
value || {}
end | [
"def",
"attributes_for",
"(",
"action",
",",
"subject",
")",
"policy",
"=",
"context",
".",
"send",
":policy",
",",
"subject",
"value",
"=",
"ModuleUtils",
".",
"try_to",
"(",
"policy",
",",
"\"attributes_for_#{action}\"",
")",
"||",
"ModuleUtils",
".",
"try_to",
"(",
"policy",
",",
"'attributes_for'",
")",
"Rails",
".",
"logger",
".",
"warn",
"I18n",
".",
"t",
"(",
"'error.pundit.not_found.attributes_for'",
",",
"subject",
":",
"subject",
")",
"unless",
"value",
"value",
"||",
"{",
"}",
"end"
] | Restrict user to assign certain values.
It will do a lookup in policy's methods and pick the first available method:
- attributes\_for\_#\{ action \}
- attributes\_for
@param action [Symbol, String]
@param subject [Object]
@return [Hash] field value paired hash that user's allowed to assign | [
"Restrict",
"user",
"to",
"assign",
"certain",
"values",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/pundit_authorization_provider.rb#L43-L48 | train |
reinteractive/wallaby | lib/authorizers/wallaby/pundit_authorization_provider.rb | Wallaby.PunditAuthorizationProvider.permit_params | def permit_params(action, subject)
policy = context.send :policy, subject
# @see https://github.com/varvet/pundit/blob/master/lib/pundit.rb#L258
ModuleUtils.try_to(policy, "permitted_attributes_for_#{action}") \
|| ModuleUtils.try_to(policy, 'permitted_attributes')
end | ruby | def permit_params(action, subject)
policy = context.send :policy, subject
# @see https://github.com/varvet/pundit/blob/master/lib/pundit.rb#L258
ModuleUtils.try_to(policy, "permitted_attributes_for_#{action}") \
|| ModuleUtils.try_to(policy, 'permitted_attributes')
end | [
"def",
"permit_params",
"(",
"action",
",",
"subject",
")",
"policy",
"=",
"context",
".",
"send",
":policy",
",",
"subject",
"# @see https://github.com/varvet/pundit/blob/master/lib/pundit.rb#L258",
"ModuleUtils",
".",
"try_to",
"(",
"policy",
",",
"\"permitted_attributes_for_#{action}\"",
")",
"||",
"ModuleUtils",
".",
"try_to",
"(",
"policy",
",",
"'permitted_attributes'",
")",
"end"
] | Restrict user for mass assignment.
It will do a lookup in policy's methods and pick the first available method:
- permitted\_attributes\_for\_#\{ action \}
- permitted\_attributes
@param action [Symbol, String]
@param subject [Object]
@return [Array] field list that user's allowed to change. | [
"Restrict",
"user",
"for",
"mass",
"assignment",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/pundit_authorization_provider.rb#L59-L64 | train |
reinteractive/wallaby | lib/concerns/wallaby/defaultable.rb | Wallaby.Defaultable.set_defaults_for | def set_defaults_for(action, options)
case action.try(:to_sym)
when :create, :update then assign_create_and_update_defaults_with options
when :destroy then assign_destroy_defaults_with options
end
options
end | ruby | def set_defaults_for(action, options)
case action.try(:to_sym)
when :create, :update then assign_create_and_update_defaults_with options
when :destroy then assign_destroy_defaults_with options
end
options
end | [
"def",
"set_defaults_for",
"(",
"action",
",",
"options",
")",
"case",
"action",
".",
"try",
"(",
":to_sym",
")",
"when",
":create",
",",
":update",
"then",
"assign_create_and_update_defaults_with",
"options",
"when",
":destroy",
"then",
"assign_destroy_defaults_with",
"options",
"end",
"options",
"end"
] | Set default options for create action
@param options [Hash]
@return [Hash] updated options with default values | [
"Set",
"default",
"options",
"for",
"create",
"action"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/concerns/wallaby/defaultable.rb#L9-L15 | train |
reinteractive/wallaby | lib/authorizers/wallaby/cancancan_authorization_provider.rb | Wallaby.CancancanAuthorizationProvider.authorize | def authorize(action, subject)
current_ability.authorize! action, subject
rescue ::CanCan::AccessDenied
Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
raise Forbidden
end | ruby | def authorize(action, subject)
current_ability.authorize! action, subject
rescue ::CanCan::AccessDenied
Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
raise Forbidden
end | [
"def",
"authorize",
"(",
"action",
",",
"subject",
")",
"current_ability",
".",
"authorize!",
"action",
",",
"subject",
"rescue",
"::",
"CanCan",
"::",
"AccessDenied",
"Rails",
".",
"logger",
".",
"info",
"I18n",
".",
"t",
"(",
"'errors.unauthorized'",
",",
"user",
":",
"user",
",",
"action",
":",
"action",
",",
"subject",
":",
"subject",
")",
"raise",
"Forbidden",
"end"
] | Check user's permission for an action on given subject.
This method will be used in controller.
@param action [Symbol, String]
@param subject [Object, Class]
@raise [Wallaby::Forbidden] when user is not authorized to perform the action. | [
"Check",
"user",
"s",
"permission",
"for",
"an",
"action",
"on",
"given",
"subject",
".",
"This",
"method",
"will",
"be",
"used",
"in",
"controller",
"."
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/cancancan_authorization_provider.rb#L19-L24 | train |
reinteractive/wallaby | lib/helpers/wallaby/links_helper.rb | Wallaby.LinksHelper.index_link | def index_link(model_class, url_params: {}, html_options: {}, &block)
return if unauthorized? :index, model_class
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
block: -> { to_model_label model_class }
)
path = index_path model_class, url_params: url_params
link_to path, html_options, &block
end | ruby | def index_link(model_class, url_params: {}, html_options: {}, &block)
return if unauthorized? :index, model_class
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
block: -> { to_model_label model_class }
)
path = index_path model_class, url_params: url_params
link_to path, html_options, &block
end | [
"def",
"index_link",
"(",
"model_class",
",",
"url_params",
":",
"{",
"}",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"return",
"if",
"unauthorized?",
":index",
",",
"model_class",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"block",
":",
"->",
"{",
"to_model_label",
"model_class",
"}",
")",
"path",
"=",
"index_path",
"model_class",
",",
"url_params",
":",
"url_params",
"link_to",
"path",
",",
"html_options",
",",
"block",
"end"
] | Return link to index page by a given model class
If user's not authorized, nil will be returned
@param model_class [Class]
@param url_params [ActionController::Parameters, Hash]
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String, nil] anchor element | [
"Return",
"link",
"to",
"index",
"page",
"by",
"a",
"given",
"model",
"class"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L17-L26 | train |
reinteractive/wallaby | lib/helpers/wallaby/links_helper.rb | Wallaby.LinksHelper.new_link | def new_link(model_class, html_options: {}, &block)
return if unauthorized? :new, model_class
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__create',
block: -> { t 'links.new', model: to_model_label(model_class) }
)
link_to new_path(model_class), html_options, &block
end | ruby | def new_link(model_class, html_options: {}, &block)
return if unauthorized? :new, model_class
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__create',
block: -> { t 'links.new', model: to_model_label(model_class) }
)
link_to new_path(model_class), html_options, &block
end | [
"def",
"new_link",
"(",
"model_class",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"return",
"if",
"unauthorized?",
":new",
",",
"model_class",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"class",
":",
"'resource__create'",
",",
"block",
":",
"->",
"{",
"t",
"'links.new'",
",",
"model",
":",
"to_model_label",
"(",
"model_class",
")",
"}",
")",
"link_to",
"new_path",
"(",
"model_class",
")",
",",
"html_options",
",",
"block",
"end"
] | Return link to create page by a given model class
If user's not authorized, nil will be returned
@param model_class [Class]
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String, nil] anchor element | [
"Return",
"link",
"to",
"create",
"page",
"by",
"a",
"given",
"model",
"class"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L34-L43 | train |
reinteractive/wallaby | lib/helpers/wallaby/links_helper.rb | Wallaby.LinksHelper.show_link | def show_link(resource, options: {}, html_options: {}, &block)
# NOTE: to_s is a must
# if a block is returning integer (e.g. `{ 1 }`)
# `link_to` will render blank text note inside hyper link
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
block: -> { decorate(resource).to_label.to_s }
)
default = options[:readonly] && block.call || nil
return default if unauthorized? :show, extract(resource)
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | ruby | def show_link(resource, options: {}, html_options: {}, &block)
# NOTE: to_s is a must
# if a block is returning integer (e.g. `{ 1 }`)
# `link_to` will render blank text note inside hyper link
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
block: -> { decorate(resource).to_label.to_s }
)
default = options[:readonly] && block.call || nil
return default if unauthorized? :show, extract(resource)
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | [
"def",
"show_link",
"(",
"resource",
",",
"options",
":",
"{",
"}",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"# NOTE: to_s is a must",
"# if a block is returning integer (e.g. `{ 1 }`)",
"# `link_to` will render blank text note inside hyper link",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"block",
":",
"->",
"{",
"decorate",
"(",
"resource",
")",
".",
"to_label",
".",
"to_s",
"}",
")",
"default",
"=",
"options",
"[",
":readonly",
"]",
"&&",
"block",
".",
"call",
"||",
"nil",
"return",
"default",
"if",
"unauthorized?",
":show",
",",
"extract",
"(",
"resource",
")",
"link_to",
"show_path",
"(",
"resource",
",",
"HashUtils",
".",
"slice!",
"(",
"options",
",",
":is_resource",
",",
":url_params",
")",
")",
",",
"html_options",
",",
"block",
"end"
] | Return link to show page by a given model class
If user's not authorized, resource label will be returned
@param resource [Object, Wallaby::ResourceDecorator] model class
@param options [Hash]
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String] anchor element / text | [
"Return",
"link",
"to",
"show",
"page",
"by",
"a",
"given",
"model",
"class",
"If",
"user",
"s",
"not",
"authorized",
"resource",
"label",
"will",
"be",
"returned"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L51-L63 | train |
reinteractive/wallaby | lib/helpers/wallaby/links_helper.rb | Wallaby.LinksHelper.edit_link | def edit_link(resource, options: {}, html_options: {}, &block)
default = options[:readonly] && decorate(resource).to_label || nil
return default if unauthorized? :edit, extract(resource)
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__update',
block: -> { "#{t 'links.edit'} #{decorate(resource).to_label}" }
)
link_to edit_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | ruby | def edit_link(resource, options: {}, html_options: {}, &block)
default = options[:readonly] && decorate(resource).to_label || nil
return default if unauthorized? :edit, extract(resource)
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__update',
block: -> { "#{t 'links.edit'} #{decorate(resource).to_label}" }
)
link_to edit_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | [
"def",
"edit_link",
"(",
"resource",
",",
"options",
":",
"{",
"}",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"default",
"=",
"options",
"[",
":readonly",
"]",
"&&",
"decorate",
"(",
"resource",
")",
".",
"to_label",
"||",
"nil",
"return",
"default",
"if",
"unauthorized?",
":edit",
",",
"extract",
"(",
"resource",
")",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"class",
":",
"'resource__update'",
",",
"block",
":",
"->",
"{",
"\"#{t 'links.edit'} #{decorate(resource).to_label}\"",
"}",
")",
"link_to",
"edit_path",
"(",
"resource",
",",
"HashUtils",
".",
"slice!",
"(",
"options",
",",
":is_resource",
",",
":url_params",
")",
")",
",",
"html_options",
",",
"block",
"end"
] | Return link to edit page by a given model class
If user's not authorized, resource label will be returned
@param resource [Object, Wallaby::ResourceDecorator] model class
@param options [Hash]
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String] anchor element / text | [
"Return",
"link",
"to",
"edit",
"page",
"by",
"a",
"given",
"model",
"class",
"If",
"user",
"s",
"not",
"authorized",
"resource",
"label",
"will",
"be",
"returned"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L71-L82 | train |
reinteractive/wallaby | lib/helpers/wallaby/links_helper.rb | Wallaby.LinksHelper.delete_link | def delete_link(resource, options: {}, html_options: {}, &block)
return if unauthorized? :destroy, extract(resource)
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__destroy',
block: -> { t 'links.delete' }
)
html_options[:method] ||= :delete
html_options[:data] ||= {}
html_options[:data][:confirm] ||= t 'links.confirm.delete'
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | ruby | def delete_link(resource, options: {}, html_options: {}, &block)
return if unauthorized? :destroy, extract(resource)
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__destroy',
block: -> { t 'links.delete' }
)
html_options[:method] ||= :delete
html_options[:data] ||= {}
html_options[:data][:confirm] ||= t 'links.confirm.delete'
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | [
"def",
"delete_link",
"(",
"resource",
",",
"options",
":",
"{",
"}",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"return",
"if",
"unauthorized?",
":destroy",
",",
"extract",
"(",
"resource",
")",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"class",
":",
"'resource__destroy'",
",",
"block",
":",
"->",
"{",
"t",
"'links.delete'",
"}",
")",
"html_options",
"[",
":method",
"]",
"||=",
":delete",
"html_options",
"[",
":data",
"]",
"||=",
"{",
"}",
"html_options",
"[",
":data",
"]",
"[",
":confirm",
"]",
"||=",
"t",
"'links.confirm.delete'",
"link_to",
"show_path",
"(",
"resource",
",",
"HashUtils",
".",
"slice!",
"(",
"options",
",",
":is_resource",
",",
":url_params",
")",
")",
",",
"html_options",
",",
"block",
"end"
] | Return link to delete action by a given model class
If user's not authorized, nil will be returned
@param resource [Object, Wallaby::ResourceDecorator] model class
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String, nil] anchor element | [
"Return",
"link",
"to",
"delete",
"action",
"by",
"a",
"given",
"model",
"class"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L90-L104 | train |
reinteractive/wallaby | lib/helpers/wallaby/links_helper.rb | Wallaby.LinksHelper.index_path | def index_path(model_class, url_params: {})
if url_params.is_a?(::ActionController::Parameters) \
&& !url_params.permitted?
url_params = {}
end
url_for url_params.to_h.reverse_merge(
resources: to_resources_name(model_class),
action: :index
)
end | ruby | def index_path(model_class, url_params: {})
if url_params.is_a?(::ActionController::Parameters) \
&& !url_params.permitted?
url_params = {}
end
url_for url_params.to_h.reverse_merge(
resources: to_resources_name(model_class),
action: :index
)
end | [
"def",
"index_path",
"(",
"model_class",
",",
"url_params",
":",
"{",
"}",
")",
"if",
"url_params",
".",
"is_a?",
"(",
"::",
"ActionController",
"::",
"Parameters",
")",
"&&",
"!",
"url_params",
".",
"permitted?",
"url_params",
"=",
"{",
"}",
"end",
"url_for",
"url_params",
".",
"to_h",
".",
"reverse_merge",
"(",
"resources",
":",
"to_resources_name",
"(",
"model_class",
")",
",",
"action",
":",
":index",
")",
"end"
] | Url for index page
@param model_class [Class]
@param url_params [ActionController::Parameters, Hash]
@return [String] | [
"Url",
"for",
"index",
"page"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L118-L128 | train |
reinteractive/wallaby | lib/helpers/wallaby/links_helper.rb | Wallaby.LinksHelper.new_path | def new_path(model_class, url_params: {})
url_for url_params.to_h.reverse_merge(
resources: to_resources_name(model_class),
action: :new
)
end | ruby | def new_path(model_class, url_params: {})
url_for url_params.to_h.reverse_merge(
resources: to_resources_name(model_class),
action: :new
)
end | [
"def",
"new_path",
"(",
"model_class",
",",
"url_params",
":",
"{",
"}",
")",
"url_for",
"url_params",
".",
"to_h",
".",
"reverse_merge",
"(",
"resources",
":",
"to_resources_name",
"(",
"model_class",
")",
",",
"action",
":",
":new",
")",
"end"
] | Url for new resource form page
@param model_class [Class]
@return [String] | [
"Url",
"for",
"new",
"resource",
"form",
"page"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L133-L138 | train |
reinteractive/wallaby | lib/helpers/wallaby/links_helper.rb | Wallaby.LinksHelper.edit_path | def edit_path(resource, is_resource: false, url_params: {})
decorated = decorate resource
return unless is_resource || decorated.primary_key_value
url_for(
url_params.to_h.reverse_merge(
resources: decorated.resources_name,
action: :edit,
id: decorated.primary_key_value
).delete_if { |_, v| v.blank? }
)
end | ruby | def edit_path(resource, is_resource: false, url_params: {})
decorated = decorate resource
return unless is_resource || decorated.primary_key_value
url_for(
url_params.to_h.reverse_merge(
resources: decorated.resources_name,
action: :edit,
id: decorated.primary_key_value
).delete_if { |_, v| v.blank? }
)
end | [
"def",
"edit_path",
"(",
"resource",
",",
"is_resource",
":",
"false",
",",
"url_params",
":",
"{",
"}",
")",
"decorated",
"=",
"decorate",
"resource",
"return",
"unless",
"is_resource",
"||",
"decorated",
".",
"primary_key_value",
"url_for",
"(",
"url_params",
".",
"to_h",
".",
"reverse_merge",
"(",
"resources",
":",
"decorated",
".",
"resources_name",
",",
"action",
":",
":edit",
",",
"id",
":",
"decorated",
".",
"primary_key_value",
")",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"blank?",
"}",
")",
"end"
] | Url for edit form page of given resource
@param resource [Object]
@param is_resource [Boolean]
@return [String] | [
"Url",
"for",
"edit",
"form",
"page",
"of",
"given",
"resource"
] | 85b86e5e661d68a62aa8ae25d39c4f545c5ac36e | https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L161-L173 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.