id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
12,800
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Image.texture_floodfill
def texture_floodfill(x, y, texture) target = pixel_color(x, y) texture_flood_fill(target, texture, x, y, FloodfillMethod) end
ruby
def texture_floodfill(x, y, texture) target = pixel_color(x, y) texture_flood_fill(target, texture, x, y, FloodfillMethod) end
[ "def", "texture_floodfill", "(", "x", ",", "y", ",", "texture", ")", "target", "=", "pixel_color", "(", "x", ",", "y", ")", "texture_flood_fill", "(", "target", ",", "texture", ",", "x", ",", "y", ",", "FloodfillMethod", ")", "end" ]
Replace matching neighboring pixels with texture pixels
[ "Replace", "matching", "neighboring", "pixels", "with", "texture", "pixels" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L985-L988
12,801
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Image.texture_fill_to_border
def texture_fill_to_border(x, y, texture) texture_flood_fill(border_color, texture, x, y, FillToBorderMethod) end
ruby
def texture_fill_to_border(x, y, texture) texture_flood_fill(border_color, texture, x, y, FillToBorderMethod) end
[ "def", "texture_fill_to_border", "(", "x", ",", "y", ",", "texture", ")", "texture_flood_fill", "(", "border_color", ",", "texture", ",", "x", ",", "y", ",", "FillToBorderMethod", ")", "end" ]
Replace neighboring pixels to border color with texture pixels
[ "Replace", "neighboring", "pixels", "to", "border", "color", "with", "texture", "pixels" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L991-L993
12,802
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Image.view
def view(x, y, width, height) view = View.new(self, x, y, width, height) return view unless block_given? begin yield(view) ensure view.sync end nil end
ruby
def view(x, y, width, height) view = View.new(self, x, y, width, height) return view unless block_given? begin yield(view) ensure view.sync end nil end
[ "def", "view", "(", "x", ",", "y", ",", "width", ",", "height", ")", "view", "=", "View", ".", "new", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ")", "return", "view", "unless", "block_given?", "begin", "yield", "(", "view", ")", "ensure", "view", ".", "sync", "end", "nil", "end" ]
Construct a view. If a block is present, yield and pass the view object, otherwise return the view object.
[ "Construct", "a", "view", ".", "If", "a", "block", "is", "present", "yield", "and", "pass", "the", "view", "object", "otherwise", "return", "the", "view", "object", "." ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L997-L1008
12,803
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.set_current
def set_current(current) if length.zero? self.scene = nil return # Don't bother looking for current image elsif scene.nil? || scene >= length self.scene = length - 1 return elsif !current.nil? # Find last instance of "current" in the list. # If "current" isn't in the list, set current to last image. self.scene = length - 1 each_with_index do |f, i| self.scene = i if f.__id__ == current end return end self.scene = length - 1 end
ruby
def set_current(current) if length.zero? self.scene = nil return # Don't bother looking for current image elsif scene.nil? || scene >= length self.scene = length - 1 return elsif !current.nil? # Find last instance of "current" in the list. # If "current" isn't in the list, set current to last image. self.scene = length - 1 each_with_index do |f, i| self.scene = i if f.__id__ == current end return end self.scene = length - 1 end
[ "def", "set_current", "(", "current", ")", "if", "length", ".", "zero?", "self", ".", "scene", "=", "nil", "return", "# Don't bother looking for current image", "elsif", "scene", ".", "nil?", "||", "scene", ">=", "length", "self", ".", "scene", "=", "length", "-", "1", "return", "elsif", "!", "current", ".", "nil?", "# Find last instance of \"current\" in the list.", "# If \"current\" isn't in the list, set current to last image.", "self", ".", "scene", "=", "length", "-", "1", "each_with_index", "do", "|", "f", ",", "i", "|", "self", ".", "scene", "=", "i", "if", "f", ".", "__id__", "==", "current", "end", "return", "end", "self", ".", "scene", "=", "length", "-", "1", "end" ]
Find old current image, update scene number current is the id of the old current image.
[ "Find", "old", "current", "image", "update", "scene", "number", "current", "is", "the", "id", "of", "the", "old", "current", "image", "." ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1248-L1266
12,804
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.scene=
def scene=(n) if n.nil? Kernel.raise IndexError, 'scene number out of bounds' unless @images.length.zero? @scene = nil return @scene elsif @images.length.zero? Kernel.raise IndexError, 'scene number out of bounds' end n = Integer(n) Kernel.raise IndexError, 'scene number out of bounds' if n < 0 || n > length - 1 @scene = n @scene end
ruby
def scene=(n) if n.nil? Kernel.raise IndexError, 'scene number out of bounds' unless @images.length.zero? @scene = nil return @scene elsif @images.length.zero? Kernel.raise IndexError, 'scene number out of bounds' end n = Integer(n) Kernel.raise IndexError, 'scene number out of bounds' if n < 0 || n > length - 1 @scene = n @scene end
[ "def", "scene", "=", "(", "n", ")", "if", "n", ".", "nil?", "Kernel", ".", "raise", "IndexError", ",", "'scene number out of bounds'", "unless", "@images", ".", "length", ".", "zero?", "@scene", "=", "nil", "return", "@scene", "elsif", "@images", ".", "length", ".", "zero?", "Kernel", ".", "raise", "IndexError", ",", "'scene number out of bounds'", "end", "n", "=", "Integer", "(", "n", ")", "Kernel", ".", "raise", "IndexError", ",", "'scene number out of bounds'", "if", "n", "<", "0", "||", "n", ">", "length", "-", "1", "@scene", "=", "n", "@scene", "end" ]
Allow scene to be set to nil
[ "Allow", "scene", "to", "be", "set", "to", "nil" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1271-L1284
12,805
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.copy
def copy ditto = self.class.new @images.each { |f| ditto << f.copy } ditto.scene = @scene ditto.taint if tainted? ditto end
ruby
def copy ditto = self.class.new @images.each { |f| ditto << f.copy } ditto.scene = @scene ditto.taint if tainted? ditto end
[ "def", "copy", "ditto", "=", "self", ".", "class", ".", "new", "@images", ".", "each", "{", "|", "f", "|", "ditto", "<<", "f", ".", "copy", "}", "ditto", ".", "scene", "=", "@scene", "ditto", ".", "taint", "if", "tainted?", "ditto", "end" ]
Make a deep copy
[ "Make", "a", "deep", "copy" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1415-L1421
12,806
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.delay=
def delay=(d) raise ArgumentError, 'delay must be greater than or equal to 0' if Integer(d) < 0 @images.each { |f| f.delay = Integer(d) } end
ruby
def delay=(d) raise ArgumentError, 'delay must be greater than or equal to 0' if Integer(d) < 0 @images.each { |f| f.delay = Integer(d) } end
[ "def", "delay", "=", "(", "d", ")", "raise", "ArgumentError", ",", "'delay must be greater than or equal to 0'", "if", "Integer", "(", "d", ")", "<", "0", "@images", ".", "each", "{", "|", "f", "|", "f", ".", "delay", "=", "Integer", "(", "d", ")", "}", "end" ]
Set same delay for all images
[ "Set", "same", "delay", "for", "all", "images" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1461-L1465
12,807
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.insert
def insert(index, *args) args.each { |image| is_an_image image } current = get_current @images.insert(index, *args) set_current current self end
ruby
def insert(index, *args) args.each { |image| is_an_image image } current = get_current @images.insert(index, *args) set_current current self end
[ "def", "insert", "(", "index", ",", "*", "args", ")", "args", ".", "each", "{", "|", "image", "|", "is_an_image", "image", "}", "current", "=", "get_current", "@images", ".", "insert", "(", "index", ",", "args", ")", "set_current", "current", "self", "end" ]
Initialize new instances
[ "Initialize", "new", "instances" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1550-L1556
12,808
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.inspect
def inspect img = [] @images.each { |image| img << image.inspect } img = '[' + img.join(",\n") + "]\nscene=#{@scene}" end
ruby
def inspect img = [] @images.each { |image| img << image.inspect } img = '[' + img.join(",\n") + "]\nscene=#{@scene}" end
[ "def", "inspect", "img", "=", "[", "]", "@images", ".", "each", "{", "|", "image", "|", "img", "<<", "image", ".", "inspect", "}", "img", "=", "'['", "+", "img", ".", "join", "(", "\",\\n\"", ")", "+", "\"]\\nscene=#{@scene}\"", "end" ]
Call inspect for all the images
[ "Call", "inspect", "for", "all", "the", "images" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1559-L1563
12,809
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.iterations=
def iterations=(n) n = Integer(n) Kernel.raise ArgumentError, 'iterations must be between 0 and 65535' if n < 0 || n > 65_535 @images.each { |f| f.iterations = n } self end
ruby
def iterations=(n) n = Integer(n) Kernel.raise ArgumentError, 'iterations must be between 0 and 65535' if n < 0 || n > 65_535 @images.each { |f| f.iterations = n } self end
[ "def", "iterations", "=", "(", "n", ")", "n", "=", "Integer", "(", "n", ")", "Kernel", ".", "raise", "ArgumentError", ",", "'iterations must be between 0 and 65535'", "if", "n", "<", "0", "||", "n", ">", "65_535", "@images", ".", "each", "{", "|", "f", "|", "f", ".", "iterations", "=", "n", "}", "self", "end" ]
Set the number of iterations of an animated GIF
[ "Set", "the", "number", "of", "iterations", "of", "an", "animated", "GIF" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1566-L1571
12,810
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.new_image
def new_image(cols, rows, *fill, &info_blk) self << Magick::Image.new(cols, rows, *fill, &info_blk) end
ruby
def new_image(cols, rows, *fill, &info_blk) self << Magick::Image.new(cols, rows, *fill, &info_blk) end
[ "def", "new_image", "(", "cols", ",", "rows", ",", "*", "fill", ",", "&", "info_blk", ")", "self", "<<", "Magick", "::", "Image", ".", "new", "(", "cols", ",", "rows", ",", "fill", ",", "info_blk", ")", "end" ]
Create a new image and add it to the end
[ "Create", "a", "new", "image", "and", "add", "it", "to", "the", "end" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1617-L1619
12,811
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.read
def read(*files, &block) Kernel.raise ArgumentError, 'no files given' if files.length.zero? files.each do |f| Magick::Image.read(f, &block).each { |n| @images << n } end @scene = length - 1 self end
ruby
def read(*files, &block) Kernel.raise ArgumentError, 'no files given' if files.length.zero? files.each do |f| Magick::Image.read(f, &block).each { |n| @images << n } end @scene = length - 1 self end
[ "def", "read", "(", "*", "files", ",", "&", "block", ")", "Kernel", ".", "raise", "ArgumentError", ",", "'no files given'", "if", "files", ".", "length", ".", "zero?", "files", ".", "each", "do", "|", "f", "|", "Magick", "::", "Image", ".", "read", "(", "f", ",", "block", ")", ".", "each", "{", "|", "n", "|", "@images", "<<", "n", "}", "end", "@scene", "=", "length", "-", "1", "self", "end" ]
Read files and concatenate the new images
[ "Read", "files", "and", "concatenate", "the", "new", "images" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1659-L1666
12,812
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.reject
def reject(&block) current = get_current ilist = self.class.new a = @images.reject(&block) a.each { |image| ilist << image } ilist.set_current current ilist end
ruby
def reject(&block) current = get_current ilist = self.class.new a = @images.reject(&block) a.each { |image| ilist << image } ilist.set_current current ilist end
[ "def", "reject", "(", "&", "block", ")", "current", "=", "get_current", "ilist", "=", "self", ".", "class", ".", "new", "a", "=", "@images", ".", "reject", "(", "block", ")", "a", ".", "each", "{", "|", "image", "|", "ilist", "<<", "image", "}", "ilist", ".", "set_current", "current", "ilist", "end" ]
override Enumerable's reject
[ "override", "Enumerable", "s", "reject" ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1669-L1676
12,813
rmagick/rmagick
examples/histogram.rb
Magick.Image.alpha_hist
def alpha_hist(freqs, scale, fg, bg) histogram = Image.new(HISTOGRAM_COLS, HISTOGRAM_ROWS) do self.background_color = bg self.border_color = fg end gc = Draw.new gc.affine(1, 0, 0, -scale, 0, HISTOGRAM_ROWS) gc.fill('white') HISTOGRAM_COLS.times do |x| gc.point(x, freqs[x]) end gc.draw(histogram) histogram['Label'] = 'Alpha' histogram end
ruby
def alpha_hist(freqs, scale, fg, bg) histogram = Image.new(HISTOGRAM_COLS, HISTOGRAM_ROWS) do self.background_color = bg self.border_color = fg end gc = Draw.new gc.affine(1, 0, 0, -scale, 0, HISTOGRAM_ROWS) gc.fill('white') HISTOGRAM_COLS.times do |x| gc.point(x, freqs[x]) end gc.draw(histogram) histogram['Label'] = 'Alpha' histogram end
[ "def", "alpha_hist", "(", "freqs", ",", "scale", ",", "fg", ",", "bg", ")", "histogram", "=", "Image", ".", "new", "(", "HISTOGRAM_COLS", ",", "HISTOGRAM_ROWS", ")", "do", "self", ".", "background_color", "=", "bg", "self", ".", "border_color", "=", "fg", "end", "gc", "=", "Draw", ".", "new", "gc", ".", "affine", "(", "1", ",", "0", ",", "0", ",", "-", "scale", ",", "0", ",", "HISTOGRAM_ROWS", ")", "gc", ".", "fill", "(", "'white'", ")", "HISTOGRAM_COLS", ".", "times", "do", "|", "x", "|", "gc", ".", "point", "(", "x", ",", "freqs", "[", "x", "]", ")", "end", "gc", ".", "draw", "(", "histogram", ")", "histogram", "[", "'Label'", "]", "=", "'Alpha'", "histogram", "end" ]
The alpha frequencies are shown as white dots.
[ "The", "alpha", "frequencies", "are", "shown", "as", "white", "dots", "." ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/examples/histogram.rb#L37-L55
12,814
rmagick/rmagick
examples/histogram.rb
Magick.Image.color_hist
def color_hist(fg, bg) img = number_colors > 256 ? quantize(256) : self begin hist = img.color_histogram rescue NotImplementedError warn 'The color_histogram method is not supported by this version '\ 'of ImageMagick/GraphicsMagick' else pixels = hist.keys.sort_by { |pixel| hist[pixel] } scale = HISTOGRAM_ROWS / (hist.values.max * AIR_FACTOR) histogram = Image.new(HISTOGRAM_COLS, HISTOGRAM_ROWS) do self.background_color = bg self.border_color = fg end x = 0 pixels.each do |pixel| column = Array.new(HISTOGRAM_ROWS).fill { Pixel.new } HISTOGRAM_ROWS.times do |y| column[y] = pixel if y >= HISTOGRAM_ROWS - (hist[pixel] * scale) end histogram.store_pixels(x, 0, 1, HISTOGRAM_ROWS, column) x = x.succ end histogram['Label'] = 'Color Frequency' return histogram end end
ruby
def color_hist(fg, bg) img = number_colors > 256 ? quantize(256) : self begin hist = img.color_histogram rescue NotImplementedError warn 'The color_histogram method is not supported by this version '\ 'of ImageMagick/GraphicsMagick' else pixels = hist.keys.sort_by { |pixel| hist[pixel] } scale = HISTOGRAM_ROWS / (hist.values.max * AIR_FACTOR) histogram = Image.new(HISTOGRAM_COLS, HISTOGRAM_ROWS) do self.background_color = bg self.border_color = fg end x = 0 pixels.each do |pixel| column = Array.new(HISTOGRAM_ROWS).fill { Pixel.new } HISTOGRAM_ROWS.times do |y| column[y] = pixel if y >= HISTOGRAM_ROWS - (hist[pixel] * scale) end histogram.store_pixels(x, 0, 1, HISTOGRAM_ROWS, column) x = x.succ end histogram['Label'] = 'Color Frequency' return histogram end end
[ "def", "color_hist", "(", "fg", ",", "bg", ")", "img", "=", "number_colors", ">", "256", "?", "quantize", "(", "256", ")", ":", "self", "begin", "hist", "=", "img", ".", "color_histogram", "rescue", "NotImplementedError", "warn", "'The color_histogram method is not supported by this version '", "'of ImageMagick/GraphicsMagick'", "else", "pixels", "=", "hist", ".", "keys", ".", "sort_by", "{", "|", "pixel", "|", "hist", "[", "pixel", "]", "}", "scale", "=", "HISTOGRAM_ROWS", "/", "(", "hist", ".", "values", ".", "max", "*", "AIR_FACTOR", ")", "histogram", "=", "Image", ".", "new", "(", "HISTOGRAM_COLS", ",", "HISTOGRAM_ROWS", ")", "do", "self", ".", "background_color", "=", "bg", "self", ".", "border_color", "=", "fg", "end", "x", "=", "0", "pixels", ".", "each", "do", "|", "pixel", "|", "column", "=", "Array", ".", "new", "(", "HISTOGRAM_ROWS", ")", ".", "fill", "{", "Pixel", ".", "new", "}", "HISTOGRAM_ROWS", ".", "times", "do", "|", "y", "|", "column", "[", "y", "]", "=", "pixel", "if", "y", ">=", "HISTOGRAM_ROWS", "-", "(", "hist", "[", "pixel", "]", "*", "scale", ")", "end", "histogram", ".", "store_pixels", "(", "x", ",", "0", ",", "1", ",", "HISTOGRAM_ROWS", ",", "column", ")", "x", "=", "x", ".", "succ", "end", "histogram", "[", "'Label'", "]", "=", "'Color Frequency'", "return", "histogram", "end", "end" ]
Make the color histogram. Quantize the image to 256 colors if necessary.
[ "Make", "the", "color", "histogram", ".", "Quantize", "the", "image", "to", "256", "colors", "if", "necessary", "." ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/examples/histogram.rb#L119-L149
12,815
rmagick/rmagick
examples/histogram.rb
Magick.Image.pixel_intensity
def pixel_intensity(pixel) (306 * (pixel.red & MAX_QUANTUM) + 601 * (pixel.green & MAX_QUANTUM) + 117 * (pixel.blue & MAX_QUANTUM)) / 1024 end
ruby
def pixel_intensity(pixel) (306 * (pixel.red & MAX_QUANTUM) + 601 * (pixel.green & MAX_QUANTUM) + 117 * (pixel.blue & MAX_QUANTUM)) / 1024 end
[ "def", "pixel_intensity", "(", "pixel", ")", "(", "306", "*", "(", "pixel", ".", "red", "&", "MAX_QUANTUM", ")", "+", "601", "*", "(", "pixel", ".", "green", "&", "MAX_QUANTUM", ")", "+", "117", "*", "(", "pixel", ".", "blue", "&", "MAX_QUANTUM", ")", ")", "/", "1024", "end" ]
Returns a value between 0 and MAX_QUANTUM. Same as the PixelIntensity macro.
[ "Returns", "a", "value", "between", "0", "and", "MAX_QUANTUM", ".", "Same", "as", "the", "PixelIntensity", "macro", "." ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/examples/histogram.rb#L190-L192
12,816
rmagick/rmagick
examples/histogram.rb
Magick.Image.histogram
def histogram(fg = 'white', bg = 'black') red = Array.new(HISTOGRAM_COLS, 0) green = Array.new(HISTOGRAM_COLS, 0) blue = Array.new(HISTOGRAM_COLS, 0) alpha = Array.new(HISTOGRAM_COLS, 0) int = Array.new(HISTOGRAM_COLS, 0) rows.times do |row| pixels = get_pixels(0, row, columns, 1) pixels.each do |pixel| red[pixel.red & MAX_QUANTUM] += 1 green[pixel.green & MAX_QUANTUM] += 1 blue[pixel.blue & MAX_QUANTUM] += 1 # Only count opacity channel if some pixels are not opaque. alpha[pixel.opacity & MAX_QUANTUM] += 1 unless opaque? v = pixel_intensity(pixel) int[v] += 1 end end # Scale to chart size. When computing the scale, add some "air" between # the max frequency and the top of the histogram. This makes a prettier chart. # The RGBA and intensity histograms are all drawn to the same scale. max = [red.max, green.max, blue.max, alpha.max, int.max].max scale = HISTOGRAM_ROWS / (max * AIR_FACTOR) charts = ImageList.new # Add the thumbnail. thumb = copy thumb['Label'] = File.basename(filename) charts << thumb # Compute the channel and intensity histograms. channel_hists = channel_histograms(red, green, blue, int, scale, fg, bg) # Add the red, green, and blue histograms to the list charts << channel_hists.shift charts << channel_hists.shift charts << channel_hists.shift # Add Alpha channel or image stats charts << if !opaque? alpha_hist(alpha, scale, fg, bg) else info_text(fg, bg) end # Add the RGB histogram charts << channel_hists.shift # Add the intensity histogram. charts << intensity_hist(channel_hists.shift) # Add the color frequency histogram. charts << color_hist(fg, bg) # Make a montage. histogram = charts.montage do self.background_color = bg self.stroke = 'transparent' self.fill = fg self.border_width = 1 self.tile = '4x2' self.geometry = "#{HISTOGRAM_COLS}x#{HISTOGRAM_ROWS}+10+10" end histogram end
ruby
def histogram(fg = 'white', bg = 'black') red = Array.new(HISTOGRAM_COLS, 0) green = Array.new(HISTOGRAM_COLS, 0) blue = Array.new(HISTOGRAM_COLS, 0) alpha = Array.new(HISTOGRAM_COLS, 0) int = Array.new(HISTOGRAM_COLS, 0) rows.times do |row| pixels = get_pixels(0, row, columns, 1) pixels.each do |pixel| red[pixel.red & MAX_QUANTUM] += 1 green[pixel.green & MAX_QUANTUM] += 1 blue[pixel.blue & MAX_QUANTUM] += 1 # Only count opacity channel if some pixels are not opaque. alpha[pixel.opacity & MAX_QUANTUM] += 1 unless opaque? v = pixel_intensity(pixel) int[v] += 1 end end # Scale to chart size. When computing the scale, add some "air" between # the max frequency and the top of the histogram. This makes a prettier chart. # The RGBA and intensity histograms are all drawn to the same scale. max = [red.max, green.max, blue.max, alpha.max, int.max].max scale = HISTOGRAM_ROWS / (max * AIR_FACTOR) charts = ImageList.new # Add the thumbnail. thumb = copy thumb['Label'] = File.basename(filename) charts << thumb # Compute the channel and intensity histograms. channel_hists = channel_histograms(red, green, blue, int, scale, fg, bg) # Add the red, green, and blue histograms to the list charts << channel_hists.shift charts << channel_hists.shift charts << channel_hists.shift # Add Alpha channel or image stats charts << if !opaque? alpha_hist(alpha, scale, fg, bg) else info_text(fg, bg) end # Add the RGB histogram charts << channel_hists.shift # Add the intensity histogram. charts << intensity_hist(channel_hists.shift) # Add the color frequency histogram. charts << color_hist(fg, bg) # Make a montage. histogram = charts.montage do self.background_color = bg self.stroke = 'transparent' self.fill = fg self.border_width = 1 self.tile = '4x2' self.geometry = "#{HISTOGRAM_COLS}x#{HISTOGRAM_ROWS}+10+10" end histogram end
[ "def", "histogram", "(", "fg", "=", "'white'", ",", "bg", "=", "'black'", ")", "red", "=", "Array", ".", "new", "(", "HISTOGRAM_COLS", ",", "0", ")", "green", "=", "Array", ".", "new", "(", "HISTOGRAM_COLS", ",", "0", ")", "blue", "=", "Array", ".", "new", "(", "HISTOGRAM_COLS", ",", "0", ")", "alpha", "=", "Array", ".", "new", "(", "HISTOGRAM_COLS", ",", "0", ")", "int", "=", "Array", ".", "new", "(", "HISTOGRAM_COLS", ",", "0", ")", "rows", ".", "times", "do", "|", "row", "|", "pixels", "=", "get_pixels", "(", "0", ",", "row", ",", "columns", ",", "1", ")", "pixels", ".", "each", "do", "|", "pixel", "|", "red", "[", "pixel", ".", "red", "&", "MAX_QUANTUM", "]", "+=", "1", "green", "[", "pixel", ".", "green", "&", "MAX_QUANTUM", "]", "+=", "1", "blue", "[", "pixel", ".", "blue", "&", "MAX_QUANTUM", "]", "+=", "1", "# Only count opacity channel if some pixels are not opaque.", "alpha", "[", "pixel", ".", "opacity", "&", "MAX_QUANTUM", "]", "+=", "1", "unless", "opaque?", "v", "=", "pixel_intensity", "(", "pixel", ")", "int", "[", "v", "]", "+=", "1", "end", "end", "# Scale to chart size. When computing the scale, add some \"air\" between", "# the max frequency and the top of the histogram. This makes a prettier chart.", "# The RGBA and intensity histograms are all drawn to the same scale.", "max", "=", "[", "red", ".", "max", ",", "green", ".", "max", ",", "blue", ".", "max", ",", "alpha", ".", "max", ",", "int", ".", "max", "]", ".", "max", "scale", "=", "HISTOGRAM_ROWS", "/", "(", "max", "*", "AIR_FACTOR", ")", "charts", "=", "ImageList", ".", "new", "# Add the thumbnail.", "thumb", "=", "copy", "thumb", "[", "'Label'", "]", "=", "File", ".", "basename", "(", "filename", ")", "charts", "<<", "thumb", "# Compute the channel and intensity histograms.", "channel_hists", "=", "channel_histograms", "(", "red", ",", "green", ",", "blue", ",", "int", ",", "scale", ",", "fg", ",", "bg", ")", "# Add the red, green, and blue histograms to the list", "charts", "<<", "channel_hists", ".", "shift", "charts", "<<", "channel_hists", ".", "shift", "charts", "<<", "channel_hists", ".", "shift", "# Add Alpha channel or image stats", "charts", "<<", "if", "!", "opaque?", "alpha_hist", "(", "alpha", ",", "scale", ",", "fg", ",", "bg", ")", "else", "info_text", "(", "fg", ",", "bg", ")", "end", "# Add the RGB histogram", "charts", "<<", "channel_hists", ".", "shift", "# Add the intensity histogram.", "charts", "<<", "intensity_hist", "(", "channel_hists", ".", "shift", ")", "# Add the color frequency histogram.", "charts", "<<", "color_hist", "(", "fg", ",", "bg", ")", "# Make a montage.", "histogram", "=", "charts", ".", "montage", "do", "self", ".", "background_color", "=", "bg", "self", ".", "stroke", "=", "'transparent'", "self", ".", "fill", "=", "fg", "self", ".", "border_width", "=", "1", "self", ".", "tile", "=", "'4x2'", "self", ".", "geometry", "=", "\"#{HISTOGRAM_COLS}x#{HISTOGRAM_ROWS}+10+10\"", "end", "histogram", "end" ]
Create the histogram montage.
[ "Create", "the", "histogram", "montage", "." ]
ef6688ed9d76bf123c2ea1a483eff8635051adb7
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/examples/histogram.rb#L197-L267
12,817
petergoldstein/dalli
lib/dalli/cas/client.rb
Dalli.Client.get_cas
def get_cas(key) (value, cas) = perform(:cas, key) value = (!value || value == 'Not found') ? nil : value if block_given? yield value, cas else [value, cas] end end
ruby
def get_cas(key) (value, cas) = perform(:cas, key) value = (!value || value == 'Not found') ? nil : value if block_given? yield value, cas else [value, cas] end end
[ "def", "get_cas", "(", "key", ")", "(", "value", ",", "cas", ")", "=", "perform", "(", ":cas", ",", "key", ")", "value", "=", "(", "!", "value", "||", "value", "==", "'Not found'", ")", "?", "nil", ":", "value", "if", "block_given?", "yield", "value", ",", "cas", "else", "[", "value", ",", "cas", "]", "end", "end" ]
Get the value and CAS ID associated with the key. If a block is provided, value and CAS will be passed to the block.
[ "Get", "the", "value", "and", "CAS", "ID", "associated", "with", "the", "key", ".", "If", "a", "block", "is", "provided", "value", "and", "CAS", "will", "be", "passed", "to", "the", "block", "." ]
5755dbfd06e333a8239f976d4b10492b4555b726
https://github.com/petergoldstein/dalli/blob/5755dbfd06e333a8239f976d4b10492b4555b726/lib/dalli/cas/client.rb#L9-L17
12,818
petergoldstein/dalli
lib/dalli/cas/client.rb
Dalli.Client.set_cas
def set_cas(key, value, cas, ttl=nil, options=nil) ttl ||= @options[:expires_in].to_i perform(:set, key, value, ttl, cas, options) end
ruby
def set_cas(key, value, cas, ttl=nil, options=nil) ttl ||= @options[:expires_in].to_i perform(:set, key, value, ttl, cas, options) end
[ "def", "set_cas", "(", "key", ",", "value", ",", "cas", ",", "ttl", "=", "nil", ",", "options", "=", "nil", ")", "ttl", "||=", "@options", "[", ":expires_in", "]", ".", "to_i", "perform", "(", ":set", ",", "key", ",", "value", ",", "ttl", ",", "cas", ",", "options", ")", "end" ]
Set the key-value pair, verifying existing CAS. Returns the resulting CAS value if succeeded, and falsy otherwise.
[ "Set", "the", "key", "-", "value", "pair", "verifying", "existing", "CAS", ".", "Returns", "the", "resulting", "CAS", "value", "if", "succeeded", "and", "falsy", "otherwise", "." ]
5755dbfd06e333a8239f976d4b10492b4555b726
https://github.com/petergoldstein/dalli/blob/5755dbfd06e333a8239f976d4b10492b4555b726/lib/dalli/cas/client.rb#L38-L41
12,819
petergoldstein/dalli
lib/dalli/client.rb
Dalli.Client.fetch
def fetch(key, ttl=nil, options=nil) options = options.nil? ? CACHE_NILS : options.merge(CACHE_NILS) if @options[:cache_nils] val = get(key, options) not_found = @options[:cache_nils] ? val == Dalli::Server::NOT_FOUND : val.nil? if not_found && block_given? val = yield add(key, val, ttl_or_default(ttl), options) end val end
ruby
def fetch(key, ttl=nil, options=nil) options = options.nil? ? CACHE_NILS : options.merge(CACHE_NILS) if @options[:cache_nils] val = get(key, options) not_found = @options[:cache_nils] ? val == Dalli::Server::NOT_FOUND : val.nil? if not_found && block_given? val = yield add(key, val, ttl_or_default(ttl), options) end val end
[ "def", "fetch", "(", "key", ",", "ttl", "=", "nil", ",", "options", "=", "nil", ")", "options", "=", "options", ".", "nil?", "?", "CACHE_NILS", ":", "options", ".", "merge", "(", "CACHE_NILS", ")", "if", "@options", "[", ":cache_nils", "]", "val", "=", "get", "(", "key", ",", "options", ")", "not_found", "=", "@options", "[", ":cache_nils", "]", "?", "val", "==", "Dalli", "::", "Server", "::", "NOT_FOUND", ":", "val", ".", "nil?", "if", "not_found", "&&", "block_given?", "val", "=", "yield", "add", "(", "key", ",", "val", ",", "ttl_or_default", "(", "ttl", ")", ",", "options", ")", "end", "val", "end" ]
Fetch the value associated with the key. If a value is found, then it is returned. If a value is not found and no block is given, then nil is returned. If a value is not found (or if the found value is nil and :cache_nils is false) and a block is given, the block will be invoked and its return value written to the cache and returned.
[ "Fetch", "the", "value", "associated", "with", "the", "key", ".", "If", "a", "value", "is", "found", "then", "it", "is", "returned", "." ]
5755dbfd06e333a8239f976d4b10492b4555b726
https://github.com/petergoldstein/dalli/blob/5755dbfd06e333a8239f976d4b10492b4555b726/lib/dalli/client.rb#L90-L101
12,820
petergoldstein/dalli
lib/dalli/client.rb
Dalli.Client.cas
def cas(key, ttl=nil, options=nil, &block) cas_core(key, false, ttl, options, &block) end
ruby
def cas(key, ttl=nil, options=nil, &block) cas_core(key, false, ttl, options, &block) end
[ "def", "cas", "(", "key", ",", "ttl", "=", "nil", ",", "options", "=", "nil", ",", "&", "block", ")", "cas_core", "(", "key", ",", "false", ",", "ttl", ",", "options", ",", "block", ")", "end" ]
compare and swap values using optimistic locking. Fetch the existing value for key. If it exists, yield the value to the block. Add the block's return value as the new value for the key. Add will fail if someone else changed the value. Returns: - nil if the key did not exist. - false if the value was changed by someone else. - true if the value was successfully updated.
[ "compare", "and", "swap", "values", "using", "optimistic", "locking", ".", "Fetch", "the", "existing", "value", "for", "key", ".", "If", "it", "exists", "yield", "the", "value", "to", "the", "block", ".", "Add", "the", "block", "s", "return", "value", "as", "the", "new", "value", "for", "the", "key", ".", "Add", "will", "fail", "if", "someone", "else", "changed", "the", "value", "." ]
5755dbfd06e333a8239f976d4b10492b4555b726
https://github.com/petergoldstein/dalli/blob/5755dbfd06e333a8239f976d4b10492b4555b726/lib/dalli/client.rb#L114-L116
12,821
petergoldstein/dalli
lib/dalli/client.rb
Dalli.Client.incr
def incr(key, amt=1, ttl=nil, default=nil) raise ArgumentError, "Positive values only: #{amt}" if amt < 0 perform(:incr, key, amt.to_i, ttl_or_default(ttl), default) end
ruby
def incr(key, amt=1, ttl=nil, default=nil) raise ArgumentError, "Positive values only: #{amt}" if amt < 0 perform(:incr, key, amt.to_i, ttl_or_default(ttl), default) end
[ "def", "incr", "(", "key", ",", "amt", "=", "1", ",", "ttl", "=", "nil", ",", "default", "=", "nil", ")", "raise", "ArgumentError", ",", "\"Positive values only: #{amt}\"", "if", "amt", "<", "0", "perform", "(", ":incr", ",", "key", ",", "amt", ".", "to_i", ",", "ttl_or_default", "(", "ttl", ")", ",", "default", ")", "end" ]
Incr adds the given amount to the counter on the memcached server. Amt must be a positive integer value. If default is nil, the counter must already exist or the operation will fail and will return nil. Otherwise this method will return the new value for the counter. Note that the ttl will only apply if the counter does not already exist. To increase an existing counter and update its TTL, use #cas.
[ "Incr", "adds", "the", "given", "amount", "to", "the", "counter", "on", "the", "memcached", "server", ".", "Amt", "must", "be", "a", "positive", "integer", "value", "." ]
5755dbfd06e333a8239f976d4b10492b4555b726
https://github.com/petergoldstein/dalli/blob/5755dbfd06e333a8239f976d4b10492b4555b726/lib/dalli/client.rb#L183-L186
12,822
petergoldstein/dalli
lib/dalli/client.rb
Dalli.Client.touch
def touch(key, ttl=nil) resp = perform(:touch, key, ttl_or_default(ttl)) resp.nil? ? nil : true end
ruby
def touch(key, ttl=nil) resp = perform(:touch, key, ttl_or_default(ttl)) resp.nil? ? nil : true end
[ "def", "touch", "(", "key", ",", "ttl", "=", "nil", ")", "resp", "=", "perform", "(", ":touch", ",", "key", ",", "ttl_or_default", "(", "ttl", ")", ")", "resp", ".", "nil?", "?", "nil", ":", "true", "end" ]
Touch updates expiration time for a given key. Returns true if key exists, otherwise nil.
[ "Touch", "updates", "expiration", "time", "for", "a", "given", "key", "." ]
5755dbfd06e333a8239f976d4b10492b4555b726
https://github.com/petergoldstein/dalli/blob/5755dbfd06e333a8239f976d4b10492b4555b726/lib/dalli/client.rb#L211-L214
12,823
petergoldstein/dalli
lib/dalli/client.rb
Dalli.Client.version
def version values = {} ring.servers.each do |server| values["#{server.name}"] = server.alive? ? server.request(:version) : nil end values end
ruby
def version values = {} ring.servers.each do |server| values["#{server.name}"] = server.alive? ? server.request(:version) : nil end values end
[ "def", "version", "values", "=", "{", "}", "ring", ".", "servers", ".", "each", "do", "|", "server", "|", "values", "[", "\"#{server.name}\"", "]", "=", "server", ".", "alive?", "?", "server", ".", "request", "(", ":version", ")", ":", "nil", "end", "values", "end" ]
Version of the memcache servers.
[ "Version", "of", "the", "memcache", "servers", "." ]
5755dbfd06e333a8239f976d4b10492b4555b726
https://github.com/petergoldstein/dalli/blob/5755dbfd06e333a8239f976d4b10492b4555b726/lib/dalli/client.rb#L245-L251
12,824
petergoldstein/dalli
lib/dalli/client.rb
Dalli.Client.get_multi_yielder
def get_multi_yielder(keys) perform do return {} if keys.empty? ring.lock do begin groups = groups_for_keys(keys) if unfound_keys = groups.delete(nil) Dalli.logger.debug { "unable to get keys for #{unfound_keys.length} keys because no matching server was found" } end make_multi_get_requests(groups) servers = groups.keys return if servers.empty? servers = perform_multi_response_start(servers) start = Time.now while true # remove any dead servers servers.delete_if { |s| s.sock.nil? } break if servers.empty? # calculate remaining timeout elapsed = Time.now - start timeout = servers.first.options[:socket_timeout] time_left = (elapsed > timeout) ? 0 : timeout - elapsed sockets = servers.map(&:sock) readable, _ = IO.select(sockets, nil, nil, time_left) if readable.nil? # no response within timeout; abort pending connections servers.each do |server| Dalli.logger.debug { "memcached at #{server.name} did not response within timeout" } server.multi_response_abort end break else readable.each do |sock| server = sock.server begin server.multi_response_nonblock.each_pair do |key, value_list| yield key_without_namespace(key), value_list end if server.multi_response_completed? servers.delete(server) end rescue NetworkError servers.delete(server) end end end end end end end end
ruby
def get_multi_yielder(keys) perform do return {} if keys.empty? ring.lock do begin groups = groups_for_keys(keys) if unfound_keys = groups.delete(nil) Dalli.logger.debug { "unable to get keys for #{unfound_keys.length} keys because no matching server was found" } end make_multi_get_requests(groups) servers = groups.keys return if servers.empty? servers = perform_multi_response_start(servers) start = Time.now while true # remove any dead servers servers.delete_if { |s| s.sock.nil? } break if servers.empty? # calculate remaining timeout elapsed = Time.now - start timeout = servers.first.options[:socket_timeout] time_left = (elapsed > timeout) ? 0 : timeout - elapsed sockets = servers.map(&:sock) readable, _ = IO.select(sockets, nil, nil, time_left) if readable.nil? # no response within timeout; abort pending connections servers.each do |server| Dalli.logger.debug { "memcached at #{server.name} did not response within timeout" } server.multi_response_abort end break else readable.each do |sock| server = sock.server begin server.multi_response_nonblock.each_pair do |key, value_list| yield key_without_namespace(key), value_list end if server.multi_response_completed? servers.delete(server) end rescue NetworkError servers.delete(server) end end end end end end end end
[ "def", "get_multi_yielder", "(", "keys", ")", "perform", "do", "return", "{", "}", "if", "keys", ".", "empty?", "ring", ".", "lock", "do", "begin", "groups", "=", "groups_for_keys", "(", "keys", ")", "if", "unfound_keys", "=", "groups", ".", "delete", "(", "nil", ")", "Dalli", ".", "logger", ".", "debug", "{", "\"unable to get keys for #{unfound_keys.length} keys because no matching server was found\"", "}", "end", "make_multi_get_requests", "(", "groups", ")", "servers", "=", "groups", ".", "keys", "return", "if", "servers", ".", "empty?", "servers", "=", "perform_multi_response_start", "(", "servers", ")", "start", "=", "Time", ".", "now", "while", "true", "# remove any dead servers", "servers", ".", "delete_if", "{", "|", "s", "|", "s", ".", "sock", ".", "nil?", "}", "break", "if", "servers", ".", "empty?", "# calculate remaining timeout", "elapsed", "=", "Time", ".", "now", "-", "start", "timeout", "=", "servers", ".", "first", ".", "options", "[", ":socket_timeout", "]", "time_left", "=", "(", "elapsed", ">", "timeout", ")", "?", "0", ":", "timeout", "-", "elapsed", "sockets", "=", "servers", ".", "map", "(", ":sock", ")", "readable", ",", "_", "=", "IO", ".", "select", "(", "sockets", ",", "nil", ",", "nil", ",", "time_left", ")", "if", "readable", ".", "nil?", "# no response within timeout; abort pending connections", "servers", ".", "each", "do", "|", "server", "|", "Dalli", ".", "logger", ".", "debug", "{", "\"memcached at #{server.name} did not response within timeout\"", "}", "server", ".", "multi_response_abort", "end", "break", "else", "readable", ".", "each", "do", "|", "sock", "|", "server", "=", "sock", ".", "server", "begin", "server", ".", "multi_response_nonblock", ".", "each_pair", "do", "|", "key", ",", "value_list", "|", "yield", "key_without_namespace", "(", "key", ")", ",", "value_list", "end", "if", "server", ".", "multi_response_completed?", "servers", ".", "delete", "(", "server", ")", "end", "rescue", "NetworkError", "servers", ".", "delete", "(", "server", ")", "end", "end", "end", "end", "end", "end", "end", "end" ]
Yields, one at a time, keys and their values+attributes.
[ "Yields", "one", "at", "a", "time", "keys", "and", "their", "values", "+", "attributes", "." ]
5755dbfd06e333a8239f976d4b10492b4555b726
https://github.com/petergoldstein/dalli/blob/5755dbfd06e333a8239f976d4b10492b4555b726/lib/dalli/client.rb#L415-L473
12,825
abonas/kubeclient
lib/kubeclient/common.rb
Kubeclient.ClientMixin.delete_entity
def delete_entity(resource_name, name, namespace = nil, delete_options: {}) delete_options_hash = delete_options.to_hash ns_prefix = build_namespace_prefix(namespace) payload = delete_options_hash.to_json unless delete_options_hash.empty? response = handle_exception do rs = rest_client[ns_prefix + resource_name + "/#{name}"] RestClient::Request.execute( rs.options.merge( method: :delete, url: rs.url, headers: { 'Content-Type' => 'application/json' }.merge(@headers), payload: payload ) ) end format_response(@as, response.body) end
ruby
def delete_entity(resource_name, name, namespace = nil, delete_options: {}) delete_options_hash = delete_options.to_hash ns_prefix = build_namespace_prefix(namespace) payload = delete_options_hash.to_json unless delete_options_hash.empty? response = handle_exception do rs = rest_client[ns_prefix + resource_name + "/#{name}"] RestClient::Request.execute( rs.options.merge( method: :delete, url: rs.url, headers: { 'Content-Type' => 'application/json' }.merge(@headers), payload: payload ) ) end format_response(@as, response.body) end
[ "def", "delete_entity", "(", "resource_name", ",", "name", ",", "namespace", "=", "nil", ",", "delete_options", ":", "{", "}", ")", "delete_options_hash", "=", "delete_options", ".", "to_hash", "ns_prefix", "=", "build_namespace_prefix", "(", "namespace", ")", "payload", "=", "delete_options_hash", ".", "to_json", "unless", "delete_options_hash", ".", "empty?", "response", "=", "handle_exception", "do", "rs", "=", "rest_client", "[", "ns_prefix", "+", "resource_name", "+", "\"/#{name}\"", "]", "RestClient", "::", "Request", ".", "execute", "(", "rs", ".", "options", ".", "merge", "(", "method", ":", ":delete", ",", "url", ":", "rs", ".", "url", ",", "headers", ":", "{", "'Content-Type'", "=>", "'application/json'", "}", ".", "merge", "(", "@headers", ")", ",", "payload", ":", "payload", ")", ")", "end", "format_response", "(", "@as", ",", "response", ".", "body", ")", "end" ]
delete_options are passed as a JSON payload in the delete request
[ "delete_options", "are", "passed", "as", "a", "JSON", "payload", "in", "the", "delete", "request" ]
3630f6c82532fba04f3e1a62d6b99c6cf2910451
https://github.com/abonas/kubeclient/blob/3630f6c82532fba04f3e1a62d6b99c6cf2910451/lib/kubeclient/common.rb#L350-L366
12,826
abonas/kubeclient
lib/kubeclient/common.rb
Kubeclient.ClientMixin.format_datetime
def format_datetime(value) case value when DateTime, Time value.strftime('%FT%T.%9N%:z') when String value else raise ArgumentError, "unsupported type '#{value.class}' of time value '#{value}'" end end
ruby
def format_datetime(value) case value when DateTime, Time value.strftime('%FT%T.%9N%:z') when String value else raise ArgumentError, "unsupported type '#{value.class}' of time value '#{value}'" end end
[ "def", "format_datetime", "(", "value", ")", "case", "value", "when", "DateTime", ",", "Time", "value", ".", "strftime", "(", "'%FT%T.%9N%:z'", ")", "when", "String", "value", "else", "raise", "ArgumentError", ",", "\"unsupported type '#{value.class}' of time value '#{value}'\"", "end", "end" ]
Format datetime according to RFC3339
[ "Format", "datetime", "according", "to", "RFC3339" ]
3630f6c82532fba04f3e1a62d6b99c6cf2910451
https://github.com/abonas/kubeclient/blob/3630f6c82532fba04f3e1a62d6b99c6cf2910451/lib/kubeclient/common.rb#L499-L508
12,827
sporkmonger/addressable
lib/addressable/template.rb
Addressable.Template.extract
def extract(uri, processor=nil) match_data = self.match(uri, processor) return (match_data ? match_data.mapping : nil) end
ruby
def extract(uri, processor=nil) match_data = self.match(uri, processor) return (match_data ? match_data.mapping : nil) end
[ "def", "extract", "(", "uri", ",", "processor", "=", "nil", ")", "match_data", "=", "self", ".", "match", "(", "uri", ",", "processor", ")", "return", "(", "match_data", "?", "match_data", ".", "mapping", ":", "nil", ")", "end" ]
Extracts a mapping from the URI using a URI Template pattern. @param [Addressable::URI, #to_str] uri The URI to extract from. @param [#restore, #match] processor A template processor object may optionally be supplied. The object should respond to either the <tt>restore</tt> or <tt>match</tt> messages or both. The <tt>restore</tt> method should take two parameters: `[String] name` and `[String] value`. The <tt>restore</tt> method should reverse any transformations that have been performed on the value to ensure a valid URI. The <tt>match</tt> method should take a single parameter: `[String] name`. The <tt>match</tt> method should return a <tt>String</tt> containing a regular expression capture group for matching on that particular variable. The default value is `".*?"`. The <tt>match</tt> method has no effect on multivariate operator expansions. @return [Hash, NilClass] The <tt>Hash</tt> mapping that was extracted from the URI, or <tt>nil</tt> if the URI didn't match the template. @example class ExampleProcessor def self.restore(name, value) return value.gsub(/\+/, " ") if name == "query" return value end def self.match(name) return ".*?" if name == "first" return ".*" end end uri = Addressable::URI.parse( "http://example.com/search/an+example+search+query/" ) Addressable::Template.new( "http://example.com/search/{query}/" ).extract(uri, ExampleProcessor) #=> {"query" => "an example search query"} uri = Addressable::URI.parse("http://example.com/a/b/c/") Addressable::Template.new( "http://example.com/{first}/{second}/" ).extract(uri, ExampleProcessor) #=> {"first" => "a", "second" => "b/c"} uri = Addressable::URI.parse("http://example.com/a/b/c/") Addressable::Template.new( "http://example.com/{first}/{-list|/|second}/" ).extract(uri) #=> {"first" => "a", "second" => ["b", "c"]}
[ "Extracts", "a", "mapping", "from", "the", "URI", "using", "a", "URI", "Template", "pattern", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/template.rb#L343-L346
12,828
sporkmonger/addressable
lib/addressable/template.rb
Addressable.Template.match
def match(uri, processor=nil) uri = Addressable::URI.parse(uri) mapping = {} # First, we need to process the pattern, and extract the values. expansions, expansion_regexp = parse_template_pattern(pattern, processor) return nil unless uri.to_str.match(expansion_regexp) unparsed_values = uri.to_str.scan(expansion_regexp).flatten if uri.to_str == pattern return Addressable::Template::MatchData.new(uri, self, mapping) elsif expansions.size > 0 index = 0 expansions.each do |expansion| _, operator, varlist = *expansion.match(EXPRESSION) varlist.split(',').each do |varspec| _, name, modifier = *varspec.match(VARSPEC) mapping[name] ||= nil case operator when nil, '+', '#', '/', '.' unparsed_value = unparsed_values[index] name = varspec[VARSPEC, 1] value = unparsed_value value = value.split(JOINERS[operator]) if value && modifier == '*' when ';', '?', '&' if modifier == '*' if unparsed_values[index] value = unparsed_values[index].split(JOINERS[operator]) value = value.inject({}) do |acc, v| key, val = v.split('=') val = "" if val.nil? acc[key] = val acc end end else if (unparsed_values[index]) name, value = unparsed_values[index].split('=') value = "" if value.nil? end end end if processor != nil && processor.respond_to?(:restore) value = processor.restore(name, value) end if processor == nil if value.is_a?(Hash) value = value.inject({}){|acc, (k, v)| acc[Addressable::URI.unencode_component(k)] = Addressable::URI.unencode_component(v) acc } elsif value.is_a?(Array) value = value.map{|v| Addressable::URI.unencode_component(v) } else value = Addressable::URI.unencode_component(value) end end if !mapping.has_key?(name) || mapping[name].nil? # Doesn't exist, set to value (even if value is nil) mapping[name] = value end index = index + 1 end end return Addressable::Template::MatchData.new(uri, self, mapping) else return nil end end
ruby
def match(uri, processor=nil) uri = Addressable::URI.parse(uri) mapping = {} # First, we need to process the pattern, and extract the values. expansions, expansion_regexp = parse_template_pattern(pattern, processor) return nil unless uri.to_str.match(expansion_regexp) unparsed_values = uri.to_str.scan(expansion_regexp).flatten if uri.to_str == pattern return Addressable::Template::MatchData.new(uri, self, mapping) elsif expansions.size > 0 index = 0 expansions.each do |expansion| _, operator, varlist = *expansion.match(EXPRESSION) varlist.split(',').each do |varspec| _, name, modifier = *varspec.match(VARSPEC) mapping[name] ||= nil case operator when nil, '+', '#', '/', '.' unparsed_value = unparsed_values[index] name = varspec[VARSPEC, 1] value = unparsed_value value = value.split(JOINERS[operator]) if value && modifier == '*' when ';', '?', '&' if modifier == '*' if unparsed_values[index] value = unparsed_values[index].split(JOINERS[operator]) value = value.inject({}) do |acc, v| key, val = v.split('=') val = "" if val.nil? acc[key] = val acc end end else if (unparsed_values[index]) name, value = unparsed_values[index].split('=') value = "" if value.nil? end end end if processor != nil && processor.respond_to?(:restore) value = processor.restore(name, value) end if processor == nil if value.is_a?(Hash) value = value.inject({}){|acc, (k, v)| acc[Addressable::URI.unencode_component(k)] = Addressable::URI.unencode_component(v) acc } elsif value.is_a?(Array) value = value.map{|v| Addressable::URI.unencode_component(v) } else value = Addressable::URI.unencode_component(value) end end if !mapping.has_key?(name) || mapping[name].nil? # Doesn't exist, set to value (even if value is nil) mapping[name] = value end index = index + 1 end end return Addressable::Template::MatchData.new(uri, self, mapping) else return nil end end
[ "def", "match", "(", "uri", ",", "processor", "=", "nil", ")", "uri", "=", "Addressable", "::", "URI", ".", "parse", "(", "uri", ")", "mapping", "=", "{", "}", "# First, we need to process the pattern, and extract the values.", "expansions", ",", "expansion_regexp", "=", "parse_template_pattern", "(", "pattern", ",", "processor", ")", "return", "nil", "unless", "uri", ".", "to_str", ".", "match", "(", "expansion_regexp", ")", "unparsed_values", "=", "uri", ".", "to_str", ".", "scan", "(", "expansion_regexp", ")", ".", "flatten", "if", "uri", ".", "to_str", "==", "pattern", "return", "Addressable", "::", "Template", "::", "MatchData", ".", "new", "(", "uri", ",", "self", ",", "mapping", ")", "elsif", "expansions", ".", "size", ">", "0", "index", "=", "0", "expansions", ".", "each", "do", "|", "expansion", "|", "_", ",", "operator", ",", "varlist", "=", "expansion", ".", "match", "(", "EXPRESSION", ")", "varlist", ".", "split", "(", "','", ")", ".", "each", "do", "|", "varspec", "|", "_", ",", "name", ",", "modifier", "=", "varspec", ".", "match", "(", "VARSPEC", ")", "mapping", "[", "name", "]", "||=", "nil", "case", "operator", "when", "nil", ",", "'+'", ",", "'#'", ",", "'/'", ",", "'.'", "unparsed_value", "=", "unparsed_values", "[", "index", "]", "name", "=", "varspec", "[", "VARSPEC", ",", "1", "]", "value", "=", "unparsed_value", "value", "=", "value", ".", "split", "(", "JOINERS", "[", "operator", "]", ")", "if", "value", "&&", "modifier", "==", "'*'", "when", "';'", ",", "'?'", ",", "'&'", "if", "modifier", "==", "'*'", "if", "unparsed_values", "[", "index", "]", "value", "=", "unparsed_values", "[", "index", "]", ".", "split", "(", "JOINERS", "[", "operator", "]", ")", "value", "=", "value", ".", "inject", "(", "{", "}", ")", "do", "|", "acc", ",", "v", "|", "key", ",", "val", "=", "v", ".", "split", "(", "'='", ")", "val", "=", "\"\"", "if", "val", ".", "nil?", "acc", "[", "key", "]", "=", "val", "acc", "end", "end", "else", "if", "(", "unparsed_values", "[", "index", "]", ")", "name", ",", "value", "=", "unparsed_values", "[", "index", "]", ".", "split", "(", "'='", ")", "value", "=", "\"\"", "if", "value", ".", "nil?", "end", "end", "end", "if", "processor", "!=", "nil", "&&", "processor", ".", "respond_to?", "(", ":restore", ")", "value", "=", "processor", ".", "restore", "(", "name", ",", "value", ")", "end", "if", "processor", "==", "nil", "if", "value", ".", "is_a?", "(", "Hash", ")", "value", "=", "value", ".", "inject", "(", "{", "}", ")", "{", "|", "acc", ",", "(", "k", ",", "v", ")", "|", "acc", "[", "Addressable", "::", "URI", ".", "unencode_component", "(", "k", ")", "]", "=", "Addressable", "::", "URI", ".", "unencode_component", "(", "v", ")", "acc", "}", "elsif", "value", ".", "is_a?", "(", "Array", ")", "value", "=", "value", ".", "map", "{", "|", "v", "|", "Addressable", "::", "URI", ".", "unencode_component", "(", "v", ")", "}", "else", "value", "=", "Addressable", "::", "URI", ".", "unencode_component", "(", "value", ")", "end", "end", "if", "!", "mapping", ".", "has_key?", "(", "name", ")", "||", "mapping", "[", "name", "]", ".", "nil?", "# Doesn't exist, set to value (even if value is nil)", "mapping", "[", "name", "]", "=", "value", "end", "index", "=", "index", "+", "1", "end", "end", "return", "Addressable", "::", "Template", "::", "MatchData", ".", "new", "(", "uri", ",", "self", ",", "mapping", ")", "else", "return", "nil", "end", "end" ]
Extracts match data from the URI using a URI Template pattern. @param [Addressable::URI, #to_str] uri The URI to extract from. @param [#restore, #match] processor A template processor object may optionally be supplied. The object should respond to either the <tt>restore</tt> or <tt>match</tt> messages or both. The <tt>restore</tt> method should take two parameters: `[String] name` and `[String] value`. The <tt>restore</tt> method should reverse any transformations that have been performed on the value to ensure a valid URI. The <tt>match</tt> method should take a single parameter: `[String] name`. The <tt>match</tt> method should return a <tt>String</tt> containing a regular expression capture group for matching on that particular variable. The default value is `".*?"`. The <tt>match</tt> method has no effect on multivariate operator expansions. @return [Hash, NilClass] The <tt>Hash</tt> mapping that was extracted from the URI, or <tt>nil</tt> if the URI didn't match the template. @example class ExampleProcessor def self.restore(name, value) return value.gsub(/\+/, " ") if name == "query" return value end def self.match(name) return ".*?" if name == "first" return ".*" end end uri = Addressable::URI.parse( "http://example.com/search/an+example+search+query/" ) match = Addressable::Template.new( "http://example.com/search/{query}/" ).match(uri, ExampleProcessor) match.variables #=> ["query"] match.captures #=> ["an example search query"] uri = Addressable::URI.parse("http://example.com/a/b/c/") match = Addressable::Template.new( "http://example.com/{first}/{+second}/" ).match(uri, ExampleProcessor) match.variables #=> ["first", "second"] match.captures #=> ["a", "b/c"] uri = Addressable::URI.parse("http://example.com/a/b/c/") match = Addressable::Template.new( "http://example.com/{first}{/second*}/" ).match(uri) match.variables #=> ["first", "second"] match.captures #=> ["a", ["b", "c"]]
[ "Extracts", "match", "data", "from", "the", "URI", "using", "a", "URI", "Template", "pattern", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/template.rb#L414-L485
12,829
sporkmonger/addressable
lib/addressable/template.rb
Addressable.Template.partial_expand
def partial_expand(mapping, processor=nil, normalize_values=true) result = self.pattern.dup mapping = normalize_keys(mapping) result.gsub!( EXPRESSION ) do |capture| transform_partial_capture(mapping, capture, processor, normalize_values) end return Addressable::Template.new(result) end
ruby
def partial_expand(mapping, processor=nil, normalize_values=true) result = self.pattern.dup mapping = normalize_keys(mapping) result.gsub!( EXPRESSION ) do |capture| transform_partial_capture(mapping, capture, processor, normalize_values) end return Addressable::Template.new(result) end
[ "def", "partial_expand", "(", "mapping", ",", "processor", "=", "nil", ",", "normalize_values", "=", "true", ")", "result", "=", "self", ".", "pattern", ".", "dup", "mapping", "=", "normalize_keys", "(", "mapping", ")", "result", ".", "gsub!", "(", "EXPRESSION", ")", "do", "|", "capture", "|", "transform_partial_capture", "(", "mapping", ",", "capture", ",", "processor", ",", "normalize_values", ")", "end", "return", "Addressable", "::", "Template", ".", "new", "(", "result", ")", "end" ]
Expands a URI template into another URI template. @param [Hash] mapping The mapping that corresponds to the pattern. @param [#validate, #transform] processor An optional processor object may be supplied. @param [Boolean] normalize_values Optional flag to enable/disable unicode normalization. Default: true The object should respond to either the <tt>validate</tt> or <tt>transform</tt> messages or both. Both the <tt>validate</tt> and <tt>transform</tt> methods should take two parameters: <tt>name</tt> and <tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt> or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid, <tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> exception will be raised if the value is invalid. The <tt>transform</tt> method should return the transformed variable value as a <tt>String</tt>. If a <tt>transform</tt> method is used, the value will not be percent encoded automatically. Unicode normalization will be performed both before and after sending the value to the transform method. @return [Addressable::Template] The partially expanded URI template. @example Addressable::Template.new( "http://example.com/{one}/{two}/" ).partial_expand({"one" => "1"}).pattern #=> "http://example.com/1/{two}/" Addressable::Template.new( "http://example.com/{?one,two}/" ).partial_expand({"one" => "1"}).pattern #=> "http://example.com/?one=1{&two}/" Addressable::Template.new( "http://example.com/{?one,two,three}/" ).partial_expand({"one" => "1", "three" => 3}).pattern #=> "http://example.com/?one=1{&two}&three=3"
[ "Expands", "a", "URI", "template", "into", "another", "URI", "template", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/template.rb#L525-L532
12,830
sporkmonger/addressable
lib/addressable/template.rb
Addressable.Template.expand
def expand(mapping, processor=nil, normalize_values=true) result = self.pattern.dup mapping = normalize_keys(mapping) result.gsub!( EXPRESSION ) do |capture| transform_capture(mapping, capture, processor, normalize_values) end return Addressable::URI.parse(result) end
ruby
def expand(mapping, processor=nil, normalize_values=true) result = self.pattern.dup mapping = normalize_keys(mapping) result.gsub!( EXPRESSION ) do |capture| transform_capture(mapping, capture, processor, normalize_values) end return Addressable::URI.parse(result) end
[ "def", "expand", "(", "mapping", ",", "processor", "=", "nil", ",", "normalize_values", "=", "true", ")", "result", "=", "self", ".", "pattern", ".", "dup", "mapping", "=", "normalize_keys", "(", "mapping", ")", "result", ".", "gsub!", "(", "EXPRESSION", ")", "do", "|", "capture", "|", "transform_capture", "(", "mapping", ",", "capture", ",", "processor", ",", "normalize_values", ")", "end", "return", "Addressable", "::", "URI", ".", "parse", "(", "result", ")", "end" ]
Expands a URI template into a full URI. @param [Hash] mapping The mapping that corresponds to the pattern. @param [#validate, #transform] processor An optional processor object may be supplied. @param [Boolean] normalize_values Optional flag to enable/disable unicode normalization. Default: true The object should respond to either the <tt>validate</tt> or <tt>transform</tt> messages or both. Both the <tt>validate</tt> and <tt>transform</tt> methods should take two parameters: <tt>name</tt> and <tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt> or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid, <tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> exception will be raised if the value is invalid. The <tt>transform</tt> method should return the transformed variable value as a <tt>String</tt>. If a <tt>transform</tt> method is used, the value will not be percent encoded automatically. Unicode normalization will be performed both before and after sending the value to the transform method. @return [Addressable::URI] The expanded URI template. @example class ExampleProcessor def self.validate(name, value) return !!(value =~ /^[\w ]+$/) if name == "query" return true end def self.transform(name, value) return value.gsub(/ /, "+") if name == "query" return value end end Addressable::Template.new( "http://example.com/search/{query}/" ).expand( {"query" => "an example search query"}, ExampleProcessor ).to_str #=> "http://example.com/search/an+example+search+query/" Addressable::Template.new( "http://example.com/search/{query}/" ).expand( {"query" => "an example search query"} ).to_str #=> "http://example.com/search/an%20example%20search%20query/" Addressable::Template.new( "http://example.com/search/{query}/" ).expand( {"query" => "bogus!"}, ExampleProcessor ).to_str #=> Addressable::Template::InvalidTemplateValueError
[ "Expands", "a", "URI", "template", "into", "a", "full", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/template.rb#L592-L599
12,831
sporkmonger/addressable
lib/addressable/template.rb
Addressable.Template.generate
def generate(params={}, recall={}, options={}) merged = recall.merge(params) if options[:processor] processor = options[:processor] elsif options[:parameterize] # TODO: This is sending me into fits trying to shoe-horn this into # the existing API. I think I've got this backwards and processors # should be a set of 4 optional blocks named :validate, :transform, # :match, and :restore. Having to use a singleton here is a huge # code smell. processor = Object.new class <<processor attr_accessor :block def transform(name, value) block.call(name, value) end end processor.block = options[:parameterize] else processor = nil end result = self.expand(merged, processor) result.to_s if result end
ruby
def generate(params={}, recall={}, options={}) merged = recall.merge(params) if options[:processor] processor = options[:processor] elsif options[:parameterize] # TODO: This is sending me into fits trying to shoe-horn this into # the existing API. I think I've got this backwards and processors # should be a set of 4 optional blocks named :validate, :transform, # :match, and :restore. Having to use a singleton here is a huge # code smell. processor = Object.new class <<processor attr_accessor :block def transform(name, value) block.call(name, value) end end processor.block = options[:parameterize] else processor = nil end result = self.expand(merged, processor) result.to_s if result end
[ "def", "generate", "(", "params", "=", "{", "}", ",", "recall", "=", "{", "}", ",", "options", "=", "{", "}", ")", "merged", "=", "recall", ".", "merge", "(", "params", ")", "if", "options", "[", ":processor", "]", "processor", "=", "options", "[", ":processor", "]", "elsif", "options", "[", ":parameterize", "]", "# TODO: This is sending me into fits trying to shoe-horn this into", "# the existing API. I think I've got this backwards and processors", "# should be a set of 4 optional blocks named :validate, :transform,", "# :match, and :restore. Having to use a singleton here is a huge", "# code smell.", "processor", "=", "Object", ".", "new", "class", "<<", "processor", "attr_accessor", ":block", "def", "transform", "(", "name", ",", "value", ")", "block", ".", "call", "(", "name", ",", "value", ")", "end", "end", "processor", ".", "block", "=", "options", "[", ":parameterize", "]", "else", "processor", "=", "nil", "end", "result", "=", "self", ".", "expand", "(", "merged", ",", "processor", ")", "result", ".", "to_s", "if", "result", "end" ]
Generates a route result for a given set of parameters. Should only be used by rack-mount. @param params [Hash] The set of parameters used to expand the template. @param recall [Hash] Default parameters used to expand the template. @param options [Hash] Either a `:processor` or a `:parameterize` block. @api private
[ "Generates", "a", "route", "result", "for", "a", "given", "set", "of", "parameters", ".", "Should", "only", "be", "used", "by", "rack", "-", "mount", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/template.rb#L665-L688
12,832
sporkmonger/addressable
lib/addressable/template.rb
Addressable.Template.transform_partial_capture
def transform_partial_capture(mapping, capture, processor = nil, normalize_values = true) _, operator, varlist = *capture.match(EXPRESSION) vars = varlist.split(",") if operator == "?" # partial expansion of form style query variables sometimes requires a # slight reordering of the variables to produce a valid url. first_to_expand = vars.find { |varspec| _, name, _ = *varspec.match(VARSPEC) mapping.key?(name) && !mapping[name].nil? } vars = [first_to_expand] + vars.reject {|varspec| varspec == first_to_expand} if first_to_expand end vars. inject("".dup) do |acc, varspec| _, name, _ = *varspec.match(VARSPEC) next_val = if mapping.key? name transform_capture(mapping, "{#{operator}#{varspec}}", processor, normalize_values) else "{#{operator}#{varspec}}" end # If we've already expanded at least one '?' operator with non-empty # value, change to '&' operator = "&" if (operator == "?") && (next_val != "") acc << next_val end end
ruby
def transform_partial_capture(mapping, capture, processor = nil, normalize_values = true) _, operator, varlist = *capture.match(EXPRESSION) vars = varlist.split(",") if operator == "?" # partial expansion of form style query variables sometimes requires a # slight reordering of the variables to produce a valid url. first_to_expand = vars.find { |varspec| _, name, _ = *varspec.match(VARSPEC) mapping.key?(name) && !mapping[name].nil? } vars = [first_to_expand] + vars.reject {|varspec| varspec == first_to_expand} if first_to_expand end vars. inject("".dup) do |acc, varspec| _, name, _ = *varspec.match(VARSPEC) next_val = if mapping.key? name transform_capture(mapping, "{#{operator}#{varspec}}", processor, normalize_values) else "{#{operator}#{varspec}}" end # If we've already expanded at least one '?' operator with non-empty # value, change to '&' operator = "&" if (operator == "?") && (next_val != "") acc << next_val end end
[ "def", "transform_partial_capture", "(", "mapping", ",", "capture", ",", "processor", "=", "nil", ",", "normalize_values", "=", "true", ")", "_", ",", "operator", ",", "varlist", "=", "capture", ".", "match", "(", "EXPRESSION", ")", "vars", "=", "varlist", ".", "split", "(", "\",\"", ")", "if", "operator", "==", "\"?\"", "# partial expansion of form style query variables sometimes requires a", "# slight reordering of the variables to produce a valid url.", "first_to_expand", "=", "vars", ".", "find", "{", "|", "varspec", "|", "_", ",", "name", ",", "_", "=", "varspec", ".", "match", "(", "VARSPEC", ")", "mapping", ".", "key?", "(", "name", ")", "&&", "!", "mapping", "[", "name", "]", ".", "nil?", "}", "vars", "=", "[", "first_to_expand", "]", "+", "vars", ".", "reject", "{", "|", "varspec", "|", "varspec", "==", "first_to_expand", "}", "if", "first_to_expand", "end", "vars", ".", "inject", "(", "\"\"", ".", "dup", ")", "do", "|", "acc", ",", "varspec", "|", "_", ",", "name", ",", "_", "=", "varspec", ".", "match", "(", "VARSPEC", ")", "next_val", "=", "if", "mapping", ".", "key?", "name", "transform_capture", "(", "mapping", ",", "\"{#{operator}#{varspec}}\"", ",", "processor", ",", "normalize_values", ")", "else", "\"{#{operator}#{varspec}}\"", "end", "# If we've already expanded at least one '?' operator with non-empty", "# value, change to '&'", "operator", "=", "\"&\"", "if", "(", "operator", "==", "\"?\"", ")", "&&", "(", "next_val", "!=", "\"\"", ")", "acc", "<<", "next_val", "end", "end" ]
Loops through each capture and expands any values available in mapping @param [Hash] mapping Set of keys to expand @param [String] capture The expression to expand @param [#validate, #transform] processor An optional processor object may be supplied. @param [Boolean] normalize_values Optional flag to enable/disable unicode normalization. Default: true The object should respond to either the <tt>validate</tt> or <tt>transform</tt> messages or both. Both the <tt>validate</tt> and <tt>transform</tt> methods should take two parameters: <tt>name</tt> and <tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt> or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid, <tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> exception will be raised if the value is invalid. The <tt>transform</tt> method should return the transformed variable value as a <tt>String</tt>. If a <tt>transform</tt> method is used, the value will not be percent encoded automatically. Unicode normalization will be performed both before and after sending the value to the transform method. @return [String] The expanded expression
[ "Loops", "through", "each", "capture", "and", "expands", "any", "values", "available", "in", "mapping" ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/template.rb#L729-L760
12,833
sporkmonger/addressable
lib/addressable/template.rb
Addressable.Template.normalize_keys
def normalize_keys(mapping) return mapping.inject({}) do |accu, pair| name, value = pair if Symbol === name name = name.to_s elsif name.respond_to?(:to_str) name = name.to_str else raise TypeError, "Can't convert #{name.class} into String." end accu[name] = value accu end end
ruby
def normalize_keys(mapping) return mapping.inject({}) do |accu, pair| name, value = pair if Symbol === name name = name.to_s elsif name.respond_to?(:to_str) name = name.to_str else raise TypeError, "Can't convert #{name.class} into String." end accu[name] = value accu end end
[ "def", "normalize_keys", "(", "mapping", ")", "return", "mapping", ".", "inject", "(", "{", "}", ")", "do", "|", "accu", ",", "pair", "|", "name", ",", "value", "=", "pair", "if", "Symbol", "===", "name", "name", "=", "name", ".", "to_s", "elsif", "name", ".", "respond_to?", "(", ":to_str", ")", "name", "=", "name", ".", "to_str", "else", "raise", "TypeError", ",", "\"Can't convert #{name.class} into String.\"", "end", "accu", "[", "name", "]", "=", "value", "accu", "end", "end" ]
Generates a hash with string keys @param [Hash] mapping A mapping hash to normalize @return [Hash] A hash with stringified keys
[ "Generates", "a", "hash", "with", "string", "keys" ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/template.rb#L960-L974
12,834
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.freeze
def freeze self.normalized_scheme self.normalized_user self.normalized_password self.normalized_userinfo self.normalized_host self.normalized_port self.normalized_authority self.normalized_site self.normalized_path self.normalized_query self.normalized_fragment self.hash super end
ruby
def freeze self.normalized_scheme self.normalized_user self.normalized_password self.normalized_userinfo self.normalized_host self.normalized_port self.normalized_authority self.normalized_site self.normalized_path self.normalized_query self.normalized_fragment self.hash super end
[ "def", "freeze", "self", ".", "normalized_scheme", "self", ".", "normalized_user", "self", ".", "normalized_password", "self", ".", "normalized_userinfo", "self", ".", "normalized_host", "self", ".", "normalized_port", "self", ".", "normalized_authority", "self", ".", "normalized_site", "self", ".", "normalized_path", "self", ".", "normalized_query", "self", ".", "normalized_fragment", "self", ".", "hash", "super", "end" ]
Creates a new uri object from component parts. @option [String, #to_str] scheme The scheme component. @option [String, #to_str] user The user component. @option [String, #to_str] password The password component. @option [String, #to_str] userinfo The userinfo component. If this is supplied, the user and password components must be omitted. @option [String, #to_str] host The host component. @option [String, #to_str] port The port component. @option [String, #to_str] authority The authority component. If this is supplied, the user, password, userinfo, host, and port components must be omitted. @option [String, #to_str] path The path component. @option [String, #to_str] query The query component. @option [String, #to_str] fragment The fragment component. @return [Addressable::URI] The constructed URI object. Freeze URI, initializing instance variables. @return [Addressable::URI] The frozen URI object.
[ "Creates", "a", "new", "uri", "object", "from", "component", "parts", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L827-L841
12,835
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_scheme
def normalized_scheme return nil unless self.scheme @normalized_scheme ||= begin if self.scheme =~ /^\s*ssh\+svn\s*$/i "svn+ssh".dup else Addressable::URI.normalize_component( self.scheme.strip.downcase, Addressable::URI::CharacterClasses::SCHEME ) end end # All normalized values should be UTF-8 @normalized_scheme.force_encoding(Encoding::UTF_8) if @normalized_scheme @normalized_scheme end
ruby
def normalized_scheme return nil unless self.scheme @normalized_scheme ||= begin if self.scheme =~ /^\s*ssh\+svn\s*$/i "svn+ssh".dup else Addressable::URI.normalize_component( self.scheme.strip.downcase, Addressable::URI::CharacterClasses::SCHEME ) end end # All normalized values should be UTF-8 @normalized_scheme.force_encoding(Encoding::UTF_8) if @normalized_scheme @normalized_scheme end
[ "def", "normalized_scheme", "return", "nil", "unless", "self", ".", "scheme", "@normalized_scheme", "||=", "begin", "if", "self", ".", "scheme", "=~", "/", "\\s", "\\+", "\\s", "/i", "\"svn+ssh\"", ".", "dup", "else", "Addressable", "::", "URI", ".", "normalize_component", "(", "self", ".", "scheme", ".", "strip", ".", "downcase", ",", "Addressable", "::", "URI", "::", "CharacterClasses", "::", "SCHEME", ")", "end", "end", "# All normalized values should be UTF-8", "@normalized_scheme", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "if", "@normalized_scheme", "@normalized_scheme", "end" ]
The scheme component for this URI, normalized. @return [String] The scheme component, normalized.
[ "The", "scheme", "component", "for", "this", "URI", "normalized", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L855-L870
12,836
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.scheme=
def scheme=(new_scheme) if new_scheme && !new_scheme.respond_to?(:to_str) raise TypeError, "Can't convert #{new_scheme.class} into String." elsif new_scheme new_scheme = new_scheme.to_str end if new_scheme && new_scheme !~ /\A[a-z][a-z0-9\.\+\-]*\z/i raise InvalidURIError, "Invalid scheme format: #{new_scheme}" end @scheme = new_scheme @scheme = nil if @scheme.to_s.strip.empty? # Reset dependent values remove_instance_variable(:@normalized_scheme) if defined?(@normalized_scheme) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def scheme=(new_scheme) if new_scheme && !new_scheme.respond_to?(:to_str) raise TypeError, "Can't convert #{new_scheme.class} into String." elsif new_scheme new_scheme = new_scheme.to_str end if new_scheme && new_scheme !~ /\A[a-z][a-z0-9\.\+\-]*\z/i raise InvalidURIError, "Invalid scheme format: #{new_scheme}" end @scheme = new_scheme @scheme = nil if @scheme.to_s.strip.empty? # Reset dependent values remove_instance_variable(:@normalized_scheme) if defined?(@normalized_scheme) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "scheme", "=", "(", "new_scheme", ")", "if", "new_scheme", "&&", "!", "new_scheme", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_scheme.class} into String.\"", "elsif", "new_scheme", "new_scheme", "=", "new_scheme", ".", "to_str", "end", "if", "new_scheme", "&&", "new_scheme", "!~", "/", "\\A", "\\.", "\\+", "\\-", "\\z", "/i", "raise", "InvalidURIError", ",", "\"Invalid scheme format: #{new_scheme}\"", "end", "@scheme", "=", "new_scheme", "@scheme", "=", "nil", "if", "@scheme", ".", "to_s", ".", "strip", ".", "empty?", "# Reset dependent values", "remove_instance_variable", "(", ":@normalized_scheme", ")", "if", "defined?", "(", "@normalized_scheme", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the scheme component for this URI. @param [String, #to_str] new_scheme The new scheme component.
[ "Sets", "the", "scheme", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L876-L894
12,837
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.user=
def user=(new_user) if new_user && !new_user.respond_to?(:to_str) raise TypeError, "Can't convert #{new_user.class} into String." end @user = new_user ? new_user.to_str : nil # You can't have a nil user with a non-nil password if password != nil @user = EMPTY_STR if @user.nil? end # Reset dependent values remove_instance_variable(:@userinfo) if defined?(@userinfo) remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo) remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_user) if defined?(@normalized_user) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def user=(new_user) if new_user && !new_user.respond_to?(:to_str) raise TypeError, "Can't convert #{new_user.class} into String." end @user = new_user ? new_user.to_str : nil # You can't have a nil user with a non-nil password if password != nil @user = EMPTY_STR if @user.nil? end # Reset dependent values remove_instance_variable(:@userinfo) if defined?(@userinfo) remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo) remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_user) if defined?(@normalized_user) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "user", "=", "(", "new_user", ")", "if", "new_user", "&&", "!", "new_user", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_user.class} into String.\"", "end", "@user", "=", "new_user", "?", "new_user", ".", "to_str", ":", "nil", "# You can't have a nil user with a non-nil password", "if", "password", "!=", "nil", "@user", "=", "EMPTY_STR", "if", "@user", ".", "nil?", "end", "# Reset dependent values", "remove_instance_variable", "(", ":@userinfo", ")", "if", "defined?", "(", "@userinfo", ")", "remove_instance_variable", "(", ":@normalized_userinfo", ")", "if", "defined?", "(", "@normalized_userinfo", ")", "remove_instance_variable", "(", ":@authority", ")", "if", "defined?", "(", "@authority", ")", "remove_instance_variable", "(", ":@normalized_user", ")", "if", "defined?", "(", "@normalized_user", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the user component for this URI. @param [String, #to_str] new_user The new user component.
[ "Sets", "the", "user", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L931-L951
12,838
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_password
def normalized_password return nil unless self.password return @normalized_password if defined?(@normalized_password) @normalized_password ||= begin if self.normalized_scheme =~ /https?/ && self.password.strip.empty? && (!self.user || self.user.strip.empty?) nil else Addressable::URI.normalize_component( self.password.strip, Addressable::URI::CharacterClasses::UNRESERVED ) end end # All normalized values should be UTF-8 if @normalized_password @normalized_password.force_encoding(Encoding::UTF_8) end @normalized_password end
ruby
def normalized_password return nil unless self.password return @normalized_password if defined?(@normalized_password) @normalized_password ||= begin if self.normalized_scheme =~ /https?/ && self.password.strip.empty? && (!self.user || self.user.strip.empty?) nil else Addressable::URI.normalize_component( self.password.strip, Addressable::URI::CharacterClasses::UNRESERVED ) end end # All normalized values should be UTF-8 if @normalized_password @normalized_password.force_encoding(Encoding::UTF_8) end @normalized_password end
[ "def", "normalized_password", "return", "nil", "unless", "self", ".", "password", "return", "@normalized_password", "if", "defined?", "(", "@normalized_password", ")", "@normalized_password", "||=", "begin", "if", "self", ".", "normalized_scheme", "=~", "/", "/", "&&", "self", ".", "password", ".", "strip", ".", "empty?", "&&", "(", "!", "self", ".", "user", "||", "self", ".", "user", ".", "strip", ".", "empty?", ")", "nil", "else", "Addressable", "::", "URI", ".", "normalize_component", "(", "self", ".", "password", ".", "strip", ",", "Addressable", "::", "URI", "::", "CharacterClasses", "::", "UNRESERVED", ")", "end", "end", "# All normalized values should be UTF-8", "if", "@normalized_password", "@normalized_password", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "end", "@normalized_password", "end" ]
The password component for this URI, normalized. @return [String] The password component, normalized.
[ "The", "password", "component", "for", "this", "URI", "normalized", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L965-L984
12,839
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.password=
def password=(new_password) if new_password && !new_password.respond_to?(:to_str) raise TypeError, "Can't convert #{new_password.class} into String." end @password = new_password ? new_password.to_str : nil # You can't have a nil user with a non-nil password @password ||= nil @user ||= nil if @password != nil @user = EMPTY_STR if @user.nil? end # Reset dependent values remove_instance_variable(:@userinfo) if defined?(@userinfo) remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo) remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_password) if defined?(@normalized_password) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def password=(new_password) if new_password && !new_password.respond_to?(:to_str) raise TypeError, "Can't convert #{new_password.class} into String." end @password = new_password ? new_password.to_str : nil # You can't have a nil user with a non-nil password @password ||= nil @user ||= nil if @password != nil @user = EMPTY_STR if @user.nil? end # Reset dependent values remove_instance_variable(:@userinfo) if defined?(@userinfo) remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo) remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_password) if defined?(@normalized_password) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "password", "=", "(", "new_password", ")", "if", "new_password", "&&", "!", "new_password", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_password.class} into String.\"", "end", "@password", "=", "new_password", "?", "new_password", ".", "to_str", ":", "nil", "# You can't have a nil user with a non-nil password", "@password", "||=", "nil", "@user", "||=", "nil", "if", "@password", "!=", "nil", "@user", "=", "EMPTY_STR", "if", "@user", ".", "nil?", "end", "# Reset dependent values", "remove_instance_variable", "(", ":@userinfo", ")", "if", "defined?", "(", "@userinfo", ")", "remove_instance_variable", "(", ":@normalized_userinfo", ")", "if", "defined?", "(", "@normalized_userinfo", ")", "remove_instance_variable", "(", ":@authority", ")", "if", "defined?", "(", "@authority", ")", "remove_instance_variable", "(", ":@normalized_password", ")", "if", "defined?", "(", "@normalized_password", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the password component for this URI. @param [String, #to_str] new_password The new password component.
[ "Sets", "the", "password", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L990-L1012
12,840
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.userinfo
def userinfo current_user = self.user current_password = self.password (current_user || current_password) && @userinfo ||= begin if current_user && current_password "#{current_user}:#{current_password}" elsif current_user && !current_password "#{current_user}" end end end
ruby
def userinfo current_user = self.user current_password = self.password (current_user || current_password) && @userinfo ||= begin if current_user && current_password "#{current_user}:#{current_password}" elsif current_user && !current_password "#{current_user}" end end end
[ "def", "userinfo", "current_user", "=", "self", ".", "user", "current_password", "=", "self", ".", "password", "(", "current_user", "||", "current_password", ")", "&&", "@userinfo", "||=", "begin", "if", "current_user", "&&", "current_password", "\"#{current_user}:#{current_password}\"", "elsif", "current_user", "&&", "!", "current_password", "\"#{current_user}\"", "end", "end", "end" ]
The userinfo component for this URI. Combines the user and password components. @return [String] The userinfo component.
[ "The", "userinfo", "component", "for", "this", "URI", ".", "Combines", "the", "user", "and", "password", "components", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1019-L1029
12,841
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_userinfo
def normalized_userinfo return nil unless self.userinfo return @normalized_userinfo if defined?(@normalized_userinfo) @normalized_userinfo ||= begin current_user = self.normalized_user current_password = self.normalized_password if !current_user && !current_password nil elsif current_user && current_password "#{current_user}:#{current_password}".dup elsif current_user && !current_password "#{current_user}".dup end end # All normalized values should be UTF-8 if @normalized_userinfo @normalized_userinfo.force_encoding(Encoding::UTF_8) end @normalized_userinfo end
ruby
def normalized_userinfo return nil unless self.userinfo return @normalized_userinfo if defined?(@normalized_userinfo) @normalized_userinfo ||= begin current_user = self.normalized_user current_password = self.normalized_password if !current_user && !current_password nil elsif current_user && current_password "#{current_user}:#{current_password}".dup elsif current_user && !current_password "#{current_user}".dup end end # All normalized values should be UTF-8 if @normalized_userinfo @normalized_userinfo.force_encoding(Encoding::UTF_8) end @normalized_userinfo end
[ "def", "normalized_userinfo", "return", "nil", "unless", "self", ".", "userinfo", "return", "@normalized_userinfo", "if", "defined?", "(", "@normalized_userinfo", ")", "@normalized_userinfo", "||=", "begin", "current_user", "=", "self", ".", "normalized_user", "current_password", "=", "self", ".", "normalized_password", "if", "!", "current_user", "&&", "!", "current_password", "nil", "elsif", "current_user", "&&", "current_password", "\"#{current_user}:#{current_password}\"", ".", "dup", "elsif", "current_user", "&&", "!", "current_password", "\"#{current_user}\"", ".", "dup", "end", "end", "# All normalized values should be UTF-8", "if", "@normalized_userinfo", "@normalized_userinfo", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "end", "@normalized_userinfo", "end" ]
The userinfo component for this URI, normalized. @return [String] The userinfo component, normalized.
[ "The", "userinfo", "component", "for", "this", "URI", "normalized", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1035-L1054
12,842
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.userinfo=
def userinfo=(new_userinfo) if new_userinfo && !new_userinfo.respond_to?(:to_str) raise TypeError, "Can't convert #{new_userinfo.class} into String." end new_user, new_password = if new_userinfo [ new_userinfo.to_str.strip[/^(.*):/, 1], new_userinfo.to_str.strip[/:(.*)$/, 1] ] else [nil, nil] end # Password assigned first to ensure validity in case of nil self.password = new_password self.user = new_user # Reset dependent values remove_instance_variable(:@authority) if defined?(@authority) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def userinfo=(new_userinfo) if new_userinfo && !new_userinfo.respond_to?(:to_str) raise TypeError, "Can't convert #{new_userinfo.class} into String." end new_user, new_password = if new_userinfo [ new_userinfo.to_str.strip[/^(.*):/, 1], new_userinfo.to_str.strip[/:(.*)$/, 1] ] else [nil, nil] end # Password assigned first to ensure validity in case of nil self.password = new_password self.user = new_user # Reset dependent values remove_instance_variable(:@authority) if defined?(@authority) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "userinfo", "=", "(", "new_userinfo", ")", "if", "new_userinfo", "&&", "!", "new_userinfo", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_userinfo.class} into String.\"", "end", "new_user", ",", "new_password", "=", "if", "new_userinfo", "[", "new_userinfo", ".", "to_str", ".", "strip", "[", "/", "/", ",", "1", "]", ",", "new_userinfo", ".", "to_str", ".", "strip", "[", "/", "/", ",", "1", "]", "]", "else", "[", "nil", ",", "nil", "]", "end", "# Password assigned first to ensure validity in case of nil", "self", ".", "password", "=", "new_password", "self", ".", "user", "=", "new_user", "# Reset dependent values", "remove_instance_variable", "(", ":@authority", ")", "if", "defined?", "(", "@authority", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the userinfo component for this URI. @param [String, #to_str] new_userinfo The new userinfo component.
[ "Sets", "the", "userinfo", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1060-L1083
12,843
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_host
def normalized_host return nil unless self.host @normalized_host ||= begin if !self.host.strip.empty? result = ::Addressable::IDNA.to_ascii( URI.unencode_component(self.host.strip.downcase) ) if result =~ /[^\.]\.$/ # Single trailing dots are unnecessary. result = result[0...-1] end result = Addressable::URI.normalize_component( result, CharacterClasses::HOST) result else EMPTY_STR.dup end end # All normalized values should be UTF-8 @normalized_host.force_encoding(Encoding::UTF_8) if @normalized_host @normalized_host end
ruby
def normalized_host return nil unless self.host @normalized_host ||= begin if !self.host.strip.empty? result = ::Addressable::IDNA.to_ascii( URI.unencode_component(self.host.strip.downcase) ) if result =~ /[^\.]\.$/ # Single trailing dots are unnecessary. result = result[0...-1] end result = Addressable::URI.normalize_component( result, CharacterClasses::HOST) result else EMPTY_STR.dup end end # All normalized values should be UTF-8 @normalized_host.force_encoding(Encoding::UTF_8) if @normalized_host @normalized_host end
[ "def", "normalized_host", "return", "nil", "unless", "self", ".", "host", "@normalized_host", "||=", "begin", "if", "!", "self", ".", "host", ".", "strip", ".", "empty?", "result", "=", "::", "Addressable", "::", "IDNA", ".", "to_ascii", "(", "URI", ".", "unencode_component", "(", "self", ".", "host", ".", "strip", ".", "downcase", ")", ")", "if", "result", "=~", "/", "\\.", "\\.", "/", "# Single trailing dots are unnecessary.", "result", "=", "result", "[", "0", "...", "-", "1", "]", "end", "result", "=", "Addressable", "::", "URI", ".", "normalize_component", "(", "result", ",", "CharacterClasses", "::", "HOST", ")", "result", "else", "EMPTY_STR", ".", "dup", "end", "end", "# All normalized values should be UTF-8", "@normalized_host", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "if", "@normalized_host", "@normalized_host", "end" ]
The host component for this URI, normalized. @return [String] The host component, normalized.
[ "The", "host", "component", "for", "this", "URI", "normalized", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1097-L1119
12,844
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.host=
def host=(new_host) if new_host && !new_host.respond_to?(:to_str) raise TypeError, "Can't convert #{new_host.class} into String." end @host = new_host ? new_host.to_str : nil # Reset dependent values remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_host) if defined?(@normalized_host) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def host=(new_host) if new_host && !new_host.respond_to?(:to_str) raise TypeError, "Can't convert #{new_host.class} into String." end @host = new_host ? new_host.to_str : nil # Reset dependent values remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_host) if defined?(@normalized_host) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "host", "=", "(", "new_host", ")", "if", "new_host", "&&", "!", "new_host", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_host.class} into String.\"", "end", "@host", "=", "new_host", "?", "new_host", ".", "to_str", ":", "nil", "# Reset dependent values", "remove_instance_variable", "(", ":@authority", ")", "if", "defined?", "(", "@authority", ")", "remove_instance_variable", "(", ":@normalized_host", ")", "if", "defined?", "(", "@normalized_host", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the host component for this URI. @param [String, #to_str] new_host The new host component.
[ "Sets", "the", "host", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1125-L1138
12,845
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.authority
def authority self.host && @authority ||= begin authority = String.new if self.userinfo != nil authority << "#{self.userinfo}@" end authority << self.host if self.port != nil authority << ":#{self.port}" end authority end end
ruby
def authority self.host && @authority ||= begin authority = String.new if self.userinfo != nil authority << "#{self.userinfo}@" end authority << self.host if self.port != nil authority << ":#{self.port}" end authority end end
[ "def", "authority", "self", ".", "host", "&&", "@authority", "||=", "begin", "authority", "=", "String", ".", "new", "if", "self", ".", "userinfo", "!=", "nil", "authority", "<<", "\"#{self.userinfo}@\"", "end", "authority", "<<", "self", ".", "host", "if", "self", ".", "port", "!=", "nil", "authority", "<<", "\":#{self.port}\"", "end", "authority", "end", "end" ]
The authority component for this URI. Combines the user, password, host, and port components. @return [String] The authority component.
[ "The", "authority", "component", "for", "this", "URI", ".", "Combines", "the", "user", "password", "host", "and", "port", "components", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1203-L1215
12,846
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_authority
def normalized_authority return nil unless self.authority @normalized_authority ||= begin authority = String.new if self.normalized_userinfo != nil authority << "#{self.normalized_userinfo}@" end authority << self.normalized_host if self.normalized_port != nil authority << ":#{self.normalized_port}" end authority end # All normalized values should be UTF-8 if @normalized_authority @normalized_authority.force_encoding(Encoding::UTF_8) end @normalized_authority end
ruby
def normalized_authority return nil unless self.authority @normalized_authority ||= begin authority = String.new if self.normalized_userinfo != nil authority << "#{self.normalized_userinfo}@" end authority << self.normalized_host if self.normalized_port != nil authority << ":#{self.normalized_port}" end authority end # All normalized values should be UTF-8 if @normalized_authority @normalized_authority.force_encoding(Encoding::UTF_8) end @normalized_authority end
[ "def", "normalized_authority", "return", "nil", "unless", "self", ".", "authority", "@normalized_authority", "||=", "begin", "authority", "=", "String", ".", "new", "if", "self", ".", "normalized_userinfo", "!=", "nil", "authority", "<<", "\"#{self.normalized_userinfo}@\"", "end", "authority", "<<", "self", ".", "normalized_host", "if", "self", ".", "normalized_port", "!=", "nil", "authority", "<<", "\":#{self.normalized_port}\"", "end", "authority", "end", "# All normalized values should be UTF-8", "if", "@normalized_authority", "@normalized_authority", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "end", "@normalized_authority", "end" ]
The authority component for this URI, normalized. @return [String] The authority component, normalized.
[ "The", "authority", "component", "for", "this", "URI", "normalized", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1221-L1239
12,847
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.authority=
def authority=(new_authority) if new_authority if !new_authority.respond_to?(:to_str) raise TypeError, "Can't convert #{new_authority.class} into String." end new_authority = new_authority.to_str new_userinfo = new_authority[/^([^\[\]]*)@/, 1] if new_userinfo new_user = new_userinfo.strip[/^([^:]*):?/, 1] new_password = new_userinfo.strip[/:(.*)$/, 1] end new_host = new_authority.sub( /^([^\[\]]*)@/, EMPTY_STR ).sub( /:([^:@\[\]]*?)$/, EMPTY_STR ) new_port = new_authority[/:([^:@\[\]]*?)$/, 1] end # Password assigned first to ensure validity in case of nil self.password = defined?(new_password) ? new_password : nil self.user = defined?(new_user) ? new_user : nil self.host = defined?(new_host) ? new_host : nil self.port = defined?(new_port) ? new_port : nil # Reset dependent values remove_instance_variable(:@userinfo) if defined?(@userinfo) remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def authority=(new_authority) if new_authority if !new_authority.respond_to?(:to_str) raise TypeError, "Can't convert #{new_authority.class} into String." end new_authority = new_authority.to_str new_userinfo = new_authority[/^([^\[\]]*)@/, 1] if new_userinfo new_user = new_userinfo.strip[/^([^:]*):?/, 1] new_password = new_userinfo.strip[/:(.*)$/, 1] end new_host = new_authority.sub( /^([^\[\]]*)@/, EMPTY_STR ).sub( /:([^:@\[\]]*?)$/, EMPTY_STR ) new_port = new_authority[/:([^:@\[\]]*?)$/, 1] end # Password assigned first to ensure validity in case of nil self.password = defined?(new_password) ? new_password : nil self.user = defined?(new_user) ? new_user : nil self.host = defined?(new_host) ? new_host : nil self.port = defined?(new_port) ? new_port : nil # Reset dependent values remove_instance_variable(:@userinfo) if defined?(@userinfo) remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "authority", "=", "(", "new_authority", ")", "if", "new_authority", "if", "!", "new_authority", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_authority.class} into String.\"", "end", "new_authority", "=", "new_authority", ".", "to_str", "new_userinfo", "=", "new_authority", "[", "/", "\\[", "\\]", "/", ",", "1", "]", "if", "new_userinfo", "new_user", "=", "new_userinfo", ".", "strip", "[", "/", "/", ",", "1", "]", "new_password", "=", "new_userinfo", ".", "strip", "[", "/", "/", ",", "1", "]", "end", "new_host", "=", "new_authority", ".", "sub", "(", "/", "\\[", "\\]", "/", ",", "EMPTY_STR", ")", ".", "sub", "(", "/", "\\[", "\\]", "/", ",", "EMPTY_STR", ")", "new_port", "=", "new_authority", "[", "/", "\\[", "\\]", "/", ",", "1", "]", "end", "# Password assigned first to ensure validity in case of nil", "self", ".", "password", "=", "defined?", "(", "new_password", ")", "?", "new_password", ":", "nil", "self", ".", "user", "=", "defined?", "(", "new_user", ")", "?", "new_user", ":", "nil", "self", ".", "host", "=", "defined?", "(", "new_host", ")", "?", "new_host", ":", "nil", "self", ".", "port", "=", "defined?", "(", "new_port", ")", "?", "new_port", ":", "nil", "# Reset dependent values", "remove_instance_variable", "(", ":@userinfo", ")", "if", "defined?", "(", "@userinfo", ")", "remove_instance_variable", "(", ":@normalized_userinfo", ")", "if", "defined?", "(", "@normalized_userinfo", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the authority component for this URI. @param [String, #to_str] new_authority The new authority component.
[ "Sets", "the", "authority", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1245-L1278
12,848
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.origin=
def origin=(new_origin) if new_origin if !new_origin.respond_to?(:to_str) raise TypeError, "Can't convert #{new_origin.class} into String." end new_origin = new_origin.to_str new_scheme = new_origin[/^([^:\/?#]+):\/\//, 1] unless new_scheme raise InvalidURIError, 'An origin cannot omit the scheme.' end new_host = new_origin[/:\/\/([^\/?#:]+)/, 1] unless new_host raise InvalidURIError, 'An origin cannot omit the host.' end new_port = new_origin[/:([^:@\[\]\/]*?)$/, 1] end self.scheme = defined?(new_scheme) ? new_scheme : nil self.host = defined?(new_host) ? new_host : nil self.port = defined?(new_port) ? new_port : nil self.userinfo = nil # Reset dependent values remove_instance_variable(:@userinfo) if defined?(@userinfo) remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo) remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_authority) if defined?(@normalized_authority) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def origin=(new_origin) if new_origin if !new_origin.respond_to?(:to_str) raise TypeError, "Can't convert #{new_origin.class} into String." end new_origin = new_origin.to_str new_scheme = new_origin[/^([^:\/?#]+):\/\//, 1] unless new_scheme raise InvalidURIError, 'An origin cannot omit the scheme.' end new_host = new_origin[/:\/\/([^\/?#:]+)/, 1] unless new_host raise InvalidURIError, 'An origin cannot omit the host.' end new_port = new_origin[/:([^:@\[\]\/]*?)$/, 1] end self.scheme = defined?(new_scheme) ? new_scheme : nil self.host = defined?(new_host) ? new_host : nil self.port = defined?(new_port) ? new_port : nil self.userinfo = nil # Reset dependent values remove_instance_variable(:@userinfo) if defined?(@userinfo) remove_instance_variable(:@normalized_userinfo) if defined?(@normalized_userinfo) remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_authority) if defined?(@normalized_authority) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "origin", "=", "(", "new_origin", ")", "if", "new_origin", "if", "!", "new_origin", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_origin.class} into String.\"", "end", "new_origin", "=", "new_origin", ".", "to_str", "new_scheme", "=", "new_origin", "[", "/", "\\/", "\\/", "\\/", "/", ",", "1", "]", "unless", "new_scheme", "raise", "InvalidURIError", ",", "'An origin cannot omit the scheme.'", "end", "new_host", "=", "new_origin", "[", "/", "\\/", "\\/", "\\/", "/", ",", "1", "]", "unless", "new_host", "raise", "InvalidURIError", ",", "'An origin cannot omit the host.'", "end", "new_port", "=", "new_origin", "[", "/", "\\[", "\\]", "\\/", "/", ",", "1", "]", "end", "self", ".", "scheme", "=", "defined?", "(", "new_scheme", ")", "?", "new_scheme", ":", "nil", "self", ".", "host", "=", "defined?", "(", "new_host", ")", "?", "new_host", ":", "nil", "self", ".", "port", "=", "defined?", "(", "new_port", ")", "?", "new_port", ":", "nil", "self", ".", "userinfo", "=", "nil", "# Reset dependent values", "remove_instance_variable", "(", ":@userinfo", ")", "if", "defined?", "(", "@userinfo", ")", "remove_instance_variable", "(", ":@normalized_userinfo", ")", "if", "defined?", "(", "@normalized_userinfo", ")", "remove_instance_variable", "(", ":@authority", ")", "if", "defined?", "(", "@authority", ")", "remove_instance_variable", "(", ":@normalized_authority", ")", "if", "defined?", "(", "@normalized_authority", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the origin for this URI, serialized to ASCII, as per RFC 6454, section 6.2. This assignment will reset the `userinfo` component. @param [String, #to_str] new_origin The new origin component.
[ "Sets", "the", "origin", "for", "this", "URI", "serialized", "to", "ASCII", "as", "per", "RFC", "6454", "section", "6", ".", "2", ".", "This", "assignment", "will", "reset", "the", "userinfo", "component", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1304-L1335
12,849
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.port=
def port=(new_port) if new_port != nil && new_port.respond_to?(:to_str) new_port = Addressable::URI.unencode_component(new_port.to_str) end if new_port.respond_to?(:valid_encoding?) && !new_port.valid_encoding? raise InvalidURIError, "Invalid encoding in port" end if new_port != nil && !(new_port.to_s =~ /^\d+$/) raise InvalidURIError, "Invalid port number: #{new_port.inspect}" end @port = new_port.to_s.to_i @port = nil if @port == 0 # Reset dependent values remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_port) if defined?(@normalized_port) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def port=(new_port) if new_port != nil && new_port.respond_to?(:to_str) new_port = Addressable::URI.unencode_component(new_port.to_str) end if new_port.respond_to?(:valid_encoding?) && !new_port.valid_encoding? raise InvalidURIError, "Invalid encoding in port" end if new_port != nil && !(new_port.to_s =~ /^\d+$/) raise InvalidURIError, "Invalid port number: #{new_port.inspect}" end @port = new_port.to_s.to_i @port = nil if @port == 0 # Reset dependent values remove_instance_variable(:@authority) if defined?(@authority) remove_instance_variable(:@normalized_port) if defined?(@normalized_port) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "port", "=", "(", "new_port", ")", "if", "new_port", "!=", "nil", "&&", "new_port", ".", "respond_to?", "(", ":to_str", ")", "new_port", "=", "Addressable", "::", "URI", ".", "unencode_component", "(", "new_port", ".", "to_str", ")", "end", "if", "new_port", ".", "respond_to?", "(", ":valid_encoding?", ")", "&&", "!", "new_port", ".", "valid_encoding?", "raise", "InvalidURIError", ",", "\"Invalid encoding in port\"", "end", "if", "new_port", "!=", "nil", "&&", "!", "(", "new_port", ".", "to_s", "=~", "/", "\\d", "/", ")", "raise", "InvalidURIError", ",", "\"Invalid port number: #{new_port.inspect}\"", "end", "@port", "=", "new_port", ".", "to_s", ".", "to_i", "@port", "=", "nil", "if", "@port", "==", "0", "# Reset dependent values", "remove_instance_variable", "(", ":@authority", ")", "if", "defined?", "(", "@authority", ")", "remove_instance_variable", "(", ":@normalized_port", ")", "if", "defined?", "(", "@normalized_port", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the port component for this URI. @param [String, Integer, #to_s] new_port The new port component.
[ "Sets", "the", "port", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1381-L1405
12,850
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.site
def site (self.scheme || self.authority) && @site ||= begin site_string = "".dup site_string << "#{self.scheme}:" if self.scheme != nil site_string << "//#{self.authority}" if self.authority != nil site_string end end
ruby
def site (self.scheme || self.authority) && @site ||= begin site_string = "".dup site_string << "#{self.scheme}:" if self.scheme != nil site_string << "//#{self.authority}" if self.authority != nil site_string end end
[ "def", "site", "(", "self", ".", "scheme", "||", "self", ".", "authority", ")", "&&", "@site", "||=", "begin", "site_string", "=", "\"\"", ".", "dup", "site_string", "<<", "\"#{self.scheme}:\"", "if", "self", ".", "scheme", "!=", "nil", "site_string", "<<", "\"//#{self.authority}\"", "if", "self", ".", "authority", "!=", "nil", "site_string", "end", "end" ]
The combination of components that represent a site. Combines the scheme, user, password, host, and port components. Primarily useful for HTTP and HTTPS. For example, <code>"http://example.com/path?query"</code> would have a <code>site</code> value of <code>"http://example.com"</code>. @return [String] The components that identify a site.
[ "The", "combination", "of", "components", "that", "represent", "a", "site", ".", "Combines", "the", "scheme", "user", "password", "host", "and", "port", "components", ".", "Primarily", "useful", "for", "HTTP", "and", "HTTPS", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1440-L1447
12,851
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_site
def normalized_site return nil unless self.site @normalized_site ||= begin site_string = "".dup if self.normalized_scheme != nil site_string << "#{self.normalized_scheme}:" end if self.normalized_authority != nil site_string << "//#{self.normalized_authority}" end site_string end # All normalized values should be UTF-8 @normalized_site.force_encoding(Encoding::UTF_8) if @normalized_site @normalized_site end
ruby
def normalized_site return nil unless self.site @normalized_site ||= begin site_string = "".dup if self.normalized_scheme != nil site_string << "#{self.normalized_scheme}:" end if self.normalized_authority != nil site_string << "//#{self.normalized_authority}" end site_string end # All normalized values should be UTF-8 @normalized_site.force_encoding(Encoding::UTF_8) if @normalized_site @normalized_site end
[ "def", "normalized_site", "return", "nil", "unless", "self", ".", "site", "@normalized_site", "||=", "begin", "site_string", "=", "\"\"", ".", "dup", "if", "self", ".", "normalized_scheme", "!=", "nil", "site_string", "<<", "\"#{self.normalized_scheme}:\"", "end", "if", "self", ".", "normalized_authority", "!=", "nil", "site_string", "<<", "\"//#{self.normalized_authority}\"", "end", "site_string", "end", "# All normalized values should be UTF-8", "@normalized_site", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "if", "@normalized_site", "@normalized_site", "end" ]
The normalized combination of components that represent a site. Combines the scheme, user, password, host, and port components. Primarily useful for HTTP and HTTPS. For example, <code>"http://example.com/path?query"</code> would have a <code>site</code> value of <code>"http://example.com"</code>. @return [String] The normalized components that identify a site.
[ "The", "normalized", "combination", "of", "components", "that", "represent", "a", "site", ".", "Combines", "the", "scheme", "user", "password", "host", "and", "port", "components", ".", "Primarily", "useful", "for", "HTTP", "and", "HTTPS", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1458-L1473
12,852
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.site=
def site=(new_site) if new_site if !new_site.respond_to?(:to_str) raise TypeError, "Can't convert #{new_site.class} into String." end new_site = new_site.to_str # These two regular expressions derived from the primary parsing # expression self.scheme = new_site[/^(?:([^:\/?#]+):)?(?:\/\/(?:[^\/?#]*))?$/, 1] self.authority = new_site[ /^(?:(?:[^:\/?#]+):)?(?:\/\/([^\/?#]*))?$/, 1 ] else self.scheme = nil self.authority = nil end end
ruby
def site=(new_site) if new_site if !new_site.respond_to?(:to_str) raise TypeError, "Can't convert #{new_site.class} into String." end new_site = new_site.to_str # These two regular expressions derived from the primary parsing # expression self.scheme = new_site[/^(?:([^:\/?#]+):)?(?:\/\/(?:[^\/?#]*))?$/, 1] self.authority = new_site[ /^(?:(?:[^:\/?#]+):)?(?:\/\/([^\/?#]*))?$/, 1 ] else self.scheme = nil self.authority = nil end end
[ "def", "site", "=", "(", "new_site", ")", "if", "new_site", "if", "!", "new_site", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_site.class} into String.\"", "end", "new_site", "=", "new_site", ".", "to_str", "# These two regular expressions derived from the primary parsing", "# expression", "self", ".", "scheme", "=", "new_site", "[", "/", "\\/", "\\/", "\\/", "\\/", "/", ",", "1", "]", "self", ".", "authority", "=", "new_site", "[", "/", "\\/", "\\/", "\\/", "\\/", "/", ",", "1", "]", "else", "self", ".", "scheme", "=", "nil", "self", ".", "authority", "=", "nil", "end", "end" ]
Sets the site value for this URI. @param [String, #to_str] new_site The new site value.
[ "Sets", "the", "site", "value", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1479-L1495
12,853
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_path
def normalized_path @normalized_path ||= begin path = self.path.to_s if self.scheme == nil && path =~ NORMPATH # Relative paths with colons in the first segment are ambiguous. path = path.sub(":", "%2F") end # String#split(delimeter, -1) uses the more strict splitting behavior # found by default in Python. result = path.strip.split(SLASH, -1).map do |segment| Addressable::URI.normalize_component( segment, Addressable::URI::CharacterClasses::PCHAR ) end.join(SLASH) result = URI.normalize_path(result) if result.empty? && ["http", "https", "ftp", "tftp"].include?(self.normalized_scheme) result = SLASH.dup end result end # All normalized values should be UTF-8 @normalized_path.force_encoding(Encoding::UTF_8) if @normalized_path @normalized_path end
ruby
def normalized_path @normalized_path ||= begin path = self.path.to_s if self.scheme == nil && path =~ NORMPATH # Relative paths with colons in the first segment are ambiguous. path = path.sub(":", "%2F") end # String#split(delimeter, -1) uses the more strict splitting behavior # found by default in Python. result = path.strip.split(SLASH, -1).map do |segment| Addressable::URI.normalize_component( segment, Addressable::URI::CharacterClasses::PCHAR ) end.join(SLASH) result = URI.normalize_path(result) if result.empty? && ["http", "https", "ftp", "tftp"].include?(self.normalized_scheme) result = SLASH.dup end result end # All normalized values should be UTF-8 @normalized_path.force_encoding(Encoding::UTF_8) if @normalized_path @normalized_path end
[ "def", "normalized_path", "@normalized_path", "||=", "begin", "path", "=", "self", ".", "path", ".", "to_s", "if", "self", ".", "scheme", "==", "nil", "&&", "path", "=~", "NORMPATH", "# Relative paths with colons in the first segment are ambiguous.", "path", "=", "path", ".", "sub", "(", "\":\"", ",", "\"%2F\"", ")", "end", "# String#split(delimeter, -1) uses the more strict splitting behavior", "# found by default in Python.", "result", "=", "path", ".", "strip", ".", "split", "(", "SLASH", ",", "-", "1", ")", ".", "map", "do", "|", "segment", "|", "Addressable", "::", "URI", ".", "normalize_component", "(", "segment", ",", "Addressable", "::", "URI", "::", "CharacterClasses", "::", "PCHAR", ")", "end", ".", "join", "(", "SLASH", ")", "result", "=", "URI", ".", "normalize_path", "(", "result", ")", "if", "result", ".", "empty?", "&&", "[", "\"http\"", ",", "\"https\"", ",", "\"ftp\"", ",", "\"tftp\"", "]", ".", "include?", "(", "self", ".", "normalized_scheme", ")", "result", "=", "SLASH", ".", "dup", "end", "result", "end", "# All normalized values should be UTF-8", "@normalized_path", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "if", "@normalized_path", "@normalized_path", "end" ]
The path component for this URI, normalized. @return [String] The path component, normalized.
[ "The", "path", "component", "for", "this", "URI", "normalized", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1510-L1536
12,854
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.path=
def path=(new_path) if new_path && !new_path.respond_to?(:to_str) raise TypeError, "Can't convert #{new_path.class} into String." end @path = (new_path || EMPTY_STR).to_str if !@path.empty? && @path[0..0] != SLASH && host != nil @path = "/#{@path}" end # Reset dependent values remove_instance_variable(:@normalized_path) if defined?(@normalized_path) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def path=(new_path) if new_path && !new_path.respond_to?(:to_str) raise TypeError, "Can't convert #{new_path.class} into String." end @path = (new_path || EMPTY_STR).to_str if !@path.empty? && @path[0..0] != SLASH && host != nil @path = "/#{@path}" end # Reset dependent values remove_instance_variable(:@normalized_path) if defined?(@normalized_path) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "path", "=", "(", "new_path", ")", "if", "new_path", "&&", "!", "new_path", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_path.class} into String.\"", "end", "@path", "=", "(", "new_path", "||", "EMPTY_STR", ")", ".", "to_str", "if", "!", "@path", ".", "empty?", "&&", "@path", "[", "0", "..", "0", "]", "!=", "SLASH", "&&", "host", "!=", "nil", "@path", "=", "\"/#{@path}\"", "end", "# Reset dependent values", "remove_instance_variable", "(", ":@normalized_path", ")", "if", "defined?", "(", "@normalized_path", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the path component for this URI. @param [String, #to_str] new_path The new path component.
[ "Sets", "the", "path", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1542-L1557
12,855
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_query
def normalized_query(*flags) return nil unless self.query return @normalized_query if defined?(@normalized_query) @normalized_query ||= begin modified_query_class = Addressable::URI::CharacterClasses::QUERY.dup # Make sure possible key-value pair delimiters are escaped. modified_query_class.sub!("\\&", "").sub!("\\;", "") pairs = (self.query || "").split("&", -1) pairs.sort! if flags.include?(:sorted) component = pairs.map do |pair| Addressable::URI.normalize_component(pair, modified_query_class, "+") end.join("&") component == "" ? nil : component end # All normalized values should be UTF-8 @normalized_query.force_encoding(Encoding::UTF_8) if @normalized_query @normalized_query end
ruby
def normalized_query(*flags) return nil unless self.query return @normalized_query if defined?(@normalized_query) @normalized_query ||= begin modified_query_class = Addressable::URI::CharacterClasses::QUERY.dup # Make sure possible key-value pair delimiters are escaped. modified_query_class.sub!("\\&", "").sub!("\\;", "") pairs = (self.query || "").split("&", -1) pairs.sort! if flags.include?(:sorted) component = pairs.map do |pair| Addressable::URI.normalize_component(pair, modified_query_class, "+") end.join("&") component == "" ? nil : component end # All normalized values should be UTF-8 @normalized_query.force_encoding(Encoding::UTF_8) if @normalized_query @normalized_query end
[ "def", "normalized_query", "(", "*", "flags", ")", "return", "nil", "unless", "self", ".", "query", "return", "@normalized_query", "if", "defined?", "(", "@normalized_query", ")", "@normalized_query", "||=", "begin", "modified_query_class", "=", "Addressable", "::", "URI", "::", "CharacterClasses", "::", "QUERY", ".", "dup", "# Make sure possible key-value pair delimiters are escaped.", "modified_query_class", ".", "sub!", "(", "\"\\\\&\"", ",", "\"\"", ")", ".", "sub!", "(", "\"\\\\;\"", ",", "\"\"", ")", "pairs", "=", "(", "self", ".", "query", "||", "\"\"", ")", ".", "split", "(", "\"&\"", ",", "-", "1", ")", "pairs", ".", "sort!", "if", "flags", ".", "include?", "(", ":sorted", ")", "component", "=", "pairs", ".", "map", "do", "|", "pair", "|", "Addressable", "::", "URI", ".", "normalize_component", "(", "pair", ",", "modified_query_class", ",", "\"+\"", ")", "end", ".", "join", "(", "\"&\"", ")", "component", "==", "\"\"", "?", "nil", ":", "component", "end", "# All normalized values should be UTF-8", "@normalized_query", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "if", "@normalized_query", "@normalized_query", "end" ]
The query component for this URI, normalized. @return [String] The query component, normalized.
[ "The", "query", "component", "for", "this", "URI", "normalized", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1590-L1607
12,856
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.query=
def query=(new_query) if new_query && !new_query.respond_to?(:to_str) raise TypeError, "Can't convert #{new_query.class} into String." end @query = new_query ? new_query.to_str : nil # Reset dependent values remove_instance_variable(:@normalized_query) if defined?(@normalized_query) remove_composite_values end
ruby
def query=(new_query) if new_query && !new_query.respond_to?(:to_str) raise TypeError, "Can't convert #{new_query.class} into String." end @query = new_query ? new_query.to_str : nil # Reset dependent values remove_instance_variable(:@normalized_query) if defined?(@normalized_query) remove_composite_values end
[ "def", "query", "=", "(", "new_query", ")", "if", "new_query", "&&", "!", "new_query", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_query.class} into String.\"", "end", "@query", "=", "new_query", "?", "new_query", ".", "to_str", ":", "nil", "# Reset dependent values", "remove_instance_variable", "(", ":@normalized_query", ")", "if", "defined?", "(", "@normalized_query", ")", "remove_composite_values", "end" ]
Sets the query component for this URI. @param [String, #to_str] new_query The new query component.
[ "Sets", "the", "query", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1613-L1622
12,857
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.query_values
def query_values(return_type=Hash) empty_accumulator = Array == return_type ? [] : {} if return_type != Hash && return_type != Array raise ArgumentError, "Invalid return type. Must be Hash or Array." end return nil if self.query == nil split_query = self.query.split("&").map do |pair| pair.split("=", 2) if pair && !pair.empty? end.compact return split_query.inject(empty_accumulator.dup) do |accu, pair| # I'd rather use key/value identifiers instead of array lookups, # but in this case I really want to maintain the exact pair structure, # so it's best to make all changes in-place. pair[0] = URI.unencode_component(pair[0]) if pair[1].respond_to?(:to_str) # I loathe the fact that I have to do this. Stupid HTML 4.01. # Treating '+' as a space was just an unbelievably bad idea. # There was nothing wrong with '%20'! # If it ain't broke, don't fix it! pair[1] = URI.unencode_component(pair[1].to_str.gsub(/\+/, " ")) end if return_type == Hash accu[pair[0]] = pair[1] else accu << pair end accu end end
ruby
def query_values(return_type=Hash) empty_accumulator = Array == return_type ? [] : {} if return_type != Hash && return_type != Array raise ArgumentError, "Invalid return type. Must be Hash or Array." end return nil if self.query == nil split_query = self.query.split("&").map do |pair| pair.split("=", 2) if pair && !pair.empty? end.compact return split_query.inject(empty_accumulator.dup) do |accu, pair| # I'd rather use key/value identifiers instead of array lookups, # but in this case I really want to maintain the exact pair structure, # so it's best to make all changes in-place. pair[0] = URI.unencode_component(pair[0]) if pair[1].respond_to?(:to_str) # I loathe the fact that I have to do this. Stupid HTML 4.01. # Treating '+' as a space was just an unbelievably bad idea. # There was nothing wrong with '%20'! # If it ain't broke, don't fix it! pair[1] = URI.unencode_component(pair[1].to_str.gsub(/\+/, " ")) end if return_type == Hash accu[pair[0]] = pair[1] else accu << pair end accu end end
[ "def", "query_values", "(", "return_type", "=", "Hash", ")", "empty_accumulator", "=", "Array", "==", "return_type", "?", "[", "]", ":", "{", "}", "if", "return_type", "!=", "Hash", "&&", "return_type", "!=", "Array", "raise", "ArgumentError", ",", "\"Invalid return type. Must be Hash or Array.\"", "end", "return", "nil", "if", "self", ".", "query", "==", "nil", "split_query", "=", "self", ".", "query", ".", "split", "(", "\"&\"", ")", ".", "map", "do", "|", "pair", "|", "pair", ".", "split", "(", "\"=\"", ",", "2", ")", "if", "pair", "&&", "!", "pair", ".", "empty?", "end", ".", "compact", "return", "split_query", ".", "inject", "(", "empty_accumulator", ".", "dup", ")", "do", "|", "accu", ",", "pair", "|", "# I'd rather use key/value identifiers instead of array lookups,", "# but in this case I really want to maintain the exact pair structure,", "# so it's best to make all changes in-place.", "pair", "[", "0", "]", "=", "URI", ".", "unencode_component", "(", "pair", "[", "0", "]", ")", "if", "pair", "[", "1", "]", ".", "respond_to?", "(", ":to_str", ")", "# I loathe the fact that I have to do this. Stupid HTML 4.01.", "# Treating '+' as a space was just an unbelievably bad idea.", "# There was nothing wrong with '%20'!", "# If it ain't broke, don't fix it!", "pair", "[", "1", "]", "=", "URI", ".", "unencode_component", "(", "pair", "[", "1", "]", ".", "to_str", ".", "gsub", "(", "/", "\\+", "/", ",", "\" \"", ")", ")", "end", "if", "return_type", "==", "Hash", "accu", "[", "pair", "[", "0", "]", "]", "=", "pair", "[", "1", "]", "else", "accu", "<<", "pair", "end", "accu", "end", "end" ]
Converts the query component to a Hash value. @param [Class] return_type The return type desired. Value must be either `Hash` or `Array`. @return [Hash, Array, nil] The query string parsed as a Hash or Array or nil if the query string is blank. @example Addressable::URI.parse("?one=1&two=2&three=3").query_values #=> {"one" => "1", "two" => "2", "three" => "3"} Addressable::URI.parse("?one=two&one=three").query_values(Array) #=> [["one", "two"], ["one", "three"]] Addressable::URI.parse("?one=two&one=three").query_values(Hash) #=> {"one" => "three"} Addressable::URI.parse("?").query_values #=> {} Addressable::URI.parse("").query_values #=> nil
[ "Converts", "the", "query", "component", "to", "a", "Hash", "value", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1644-L1672
12,858
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.query_values=
def query_values=(new_query_values) if new_query_values == nil self.query = nil return nil end if !new_query_values.is_a?(Array) if !new_query_values.respond_to?(:to_hash) raise TypeError, "Can't convert #{new_query_values.class} into Hash." end new_query_values = new_query_values.to_hash new_query_values = new_query_values.map do |key, value| key = key.to_s if key.kind_of?(Symbol) [key, value] end # Useful default for OAuth and caching. # Only to be used for non-Array inputs. Arrays should preserve order. new_query_values.sort! end # new_query_values have form [['key1', 'value1'], ['key2', 'value2']] buffer = "".dup new_query_values.each do |key, value| encoded_key = URI.encode_component( key, CharacterClasses::UNRESERVED ) if value == nil buffer << "#{encoded_key}&" elsif value.kind_of?(Array) value.each do |sub_value| encoded_value = URI.encode_component( sub_value, CharacterClasses::UNRESERVED ) buffer << "#{encoded_key}=#{encoded_value}&" end else encoded_value = URI.encode_component( value, CharacterClasses::UNRESERVED ) buffer << "#{encoded_key}=#{encoded_value}&" end end self.query = buffer.chop end
ruby
def query_values=(new_query_values) if new_query_values == nil self.query = nil return nil end if !new_query_values.is_a?(Array) if !new_query_values.respond_to?(:to_hash) raise TypeError, "Can't convert #{new_query_values.class} into Hash." end new_query_values = new_query_values.to_hash new_query_values = new_query_values.map do |key, value| key = key.to_s if key.kind_of?(Symbol) [key, value] end # Useful default for OAuth and caching. # Only to be used for non-Array inputs. Arrays should preserve order. new_query_values.sort! end # new_query_values have form [['key1', 'value1'], ['key2', 'value2']] buffer = "".dup new_query_values.each do |key, value| encoded_key = URI.encode_component( key, CharacterClasses::UNRESERVED ) if value == nil buffer << "#{encoded_key}&" elsif value.kind_of?(Array) value.each do |sub_value| encoded_value = URI.encode_component( sub_value, CharacterClasses::UNRESERVED ) buffer << "#{encoded_key}=#{encoded_value}&" end else encoded_value = URI.encode_component( value, CharacterClasses::UNRESERVED ) buffer << "#{encoded_key}=#{encoded_value}&" end end self.query = buffer.chop end
[ "def", "query_values", "=", "(", "new_query_values", ")", "if", "new_query_values", "==", "nil", "self", ".", "query", "=", "nil", "return", "nil", "end", "if", "!", "new_query_values", ".", "is_a?", "(", "Array", ")", "if", "!", "new_query_values", ".", "respond_to?", "(", ":to_hash", ")", "raise", "TypeError", ",", "\"Can't convert #{new_query_values.class} into Hash.\"", "end", "new_query_values", "=", "new_query_values", ".", "to_hash", "new_query_values", "=", "new_query_values", ".", "map", "do", "|", "key", ",", "value", "|", "key", "=", "key", ".", "to_s", "if", "key", ".", "kind_of?", "(", "Symbol", ")", "[", "key", ",", "value", "]", "end", "# Useful default for OAuth and caching.", "# Only to be used for non-Array inputs. Arrays should preserve order.", "new_query_values", ".", "sort!", "end", "# new_query_values have form [['key1', 'value1'], ['key2', 'value2']]", "buffer", "=", "\"\"", ".", "dup", "new_query_values", ".", "each", "do", "|", "key", ",", "value", "|", "encoded_key", "=", "URI", ".", "encode_component", "(", "key", ",", "CharacterClasses", "::", "UNRESERVED", ")", "if", "value", "==", "nil", "buffer", "<<", "\"#{encoded_key}&\"", "elsif", "value", ".", "kind_of?", "(", "Array", ")", "value", ".", "each", "do", "|", "sub_value", "|", "encoded_value", "=", "URI", ".", "encode_component", "(", "sub_value", ",", "CharacterClasses", "::", "UNRESERVED", ")", "buffer", "<<", "\"#{encoded_key}=#{encoded_value}&\"", "end", "else", "encoded_value", "=", "URI", ".", "encode_component", "(", "value", ",", "CharacterClasses", "::", "UNRESERVED", ")", "buffer", "<<", "\"#{encoded_key}=#{encoded_value}&\"", "end", "end", "self", ".", "query", "=", "buffer", ".", "chop", "end" ]
Sets the query component for this URI from a Hash object. An empty Hash or Array will result in an empty query string. @param [Hash, #to_hash, Array] new_query_values The new query values. @example uri.query_values = {:a => "a", :b => ["c", "d", "e"]} uri.query # => "a=a&b=c&b=d&b=e" uri.query_values = [['a', 'a'], ['b', 'c'], ['b', 'd'], ['b', 'e']] uri.query # => "a=a&b=c&b=d&b=e" uri.query_values = [['a', 'a'], ['b', ['c', 'd', 'e']]] uri.query # => "a=a&b=c&b=d&b=e" uri.query_values = [['flag'], ['key', 'value']] uri.query # => "flag&key=value"
[ "Sets", "the", "query", "component", "for", "this", "URI", "from", "a", "Hash", "object", ".", "An", "empty", "Hash", "or", "Array", "will", "result", "in", "an", "empty", "query", "string", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1693-L1737
12,859
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.request_uri=
def request_uri=(new_request_uri) if !new_request_uri.respond_to?(:to_str) raise TypeError, "Can't convert #{new_request_uri.class} into String." end if self.absolute? && self.scheme !~ /^https?$/i raise InvalidURIError, "Cannot set an HTTP request URI for a non-HTTP URI." end new_request_uri = new_request_uri.to_str path_component = new_request_uri[/^([^\?]*)\??(?:.*)$/, 1] query_component = new_request_uri[/^(?:[^\?]*)\?(.*)$/, 1] path_component = path_component.to_s path_component = (!path_component.empty? ? path_component : SLASH) self.path = path_component self.query = query_component # Reset dependent values remove_composite_values end
ruby
def request_uri=(new_request_uri) if !new_request_uri.respond_to?(:to_str) raise TypeError, "Can't convert #{new_request_uri.class} into String." end if self.absolute? && self.scheme !~ /^https?$/i raise InvalidURIError, "Cannot set an HTTP request URI for a non-HTTP URI." end new_request_uri = new_request_uri.to_str path_component = new_request_uri[/^([^\?]*)\??(?:.*)$/, 1] query_component = new_request_uri[/^(?:[^\?]*)\?(.*)$/, 1] path_component = path_component.to_s path_component = (!path_component.empty? ? path_component : SLASH) self.path = path_component self.query = query_component # Reset dependent values remove_composite_values end
[ "def", "request_uri", "=", "(", "new_request_uri", ")", "if", "!", "new_request_uri", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_request_uri.class} into String.\"", "end", "if", "self", ".", "absolute?", "&&", "self", ".", "scheme", "!~", "/", "/i", "raise", "InvalidURIError", ",", "\"Cannot set an HTTP request URI for a non-HTTP URI.\"", "end", "new_request_uri", "=", "new_request_uri", ".", "to_str", "path_component", "=", "new_request_uri", "[", "/", "\\?", "\\?", "/", ",", "1", "]", "query_component", "=", "new_request_uri", "[", "/", "\\?", "\\?", "/", ",", "1", "]", "path_component", "=", "path_component", ".", "to_s", "path_component", "=", "(", "!", "path_component", ".", "empty?", "?", "path_component", ":", "SLASH", ")", "self", ".", "path", "=", "path_component", "self", ".", "query", "=", "query_component", "# Reset dependent values", "remove_composite_values", "end" ]
Sets the HTTP request URI for this URI. @param [String, #to_str] new_request_uri The new HTTP request URI.
[ "Sets", "the", "HTTP", "request", "URI", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1756-L1774
12,860
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalized_fragment
def normalized_fragment return nil unless self.fragment return @normalized_fragment if defined?(@normalized_fragment) @normalized_fragment ||= begin component = Addressable::URI.normalize_component( self.fragment, Addressable::URI::CharacterClasses::FRAGMENT ) component == "" ? nil : component end # All normalized values should be UTF-8 if @normalized_fragment @normalized_fragment.force_encoding(Encoding::UTF_8) end @normalized_fragment end
ruby
def normalized_fragment return nil unless self.fragment return @normalized_fragment if defined?(@normalized_fragment) @normalized_fragment ||= begin component = Addressable::URI.normalize_component( self.fragment, Addressable::URI::CharacterClasses::FRAGMENT ) component == "" ? nil : component end # All normalized values should be UTF-8 if @normalized_fragment @normalized_fragment.force_encoding(Encoding::UTF_8) end @normalized_fragment end
[ "def", "normalized_fragment", "return", "nil", "unless", "self", ".", "fragment", "return", "@normalized_fragment", "if", "defined?", "(", "@normalized_fragment", ")", "@normalized_fragment", "||=", "begin", "component", "=", "Addressable", "::", "URI", ".", "normalize_component", "(", "self", ".", "fragment", ",", "Addressable", "::", "URI", "::", "CharacterClasses", "::", "FRAGMENT", ")", "component", "==", "\"\"", "?", "nil", ":", "component", "end", "# All normalized values should be UTF-8", "if", "@normalized_fragment", "@normalized_fragment", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", "end", "@normalized_fragment", "end" ]
The fragment component for this URI, normalized. @return [String] The fragment component, normalized.
[ "The", "fragment", "component", "for", "this", "URI", "normalized", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1788-L1803
12,861
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.fragment=
def fragment=(new_fragment) if new_fragment && !new_fragment.respond_to?(:to_str) raise TypeError, "Can't convert #{new_fragment.class} into String." end @fragment = new_fragment ? new_fragment.to_str : nil # Reset dependent values remove_instance_variable(:@normalized_fragment) if defined?(@normalized_fragment) remove_composite_values # Ensure we haven't created an invalid URI validate() end
ruby
def fragment=(new_fragment) if new_fragment && !new_fragment.respond_to?(:to_str) raise TypeError, "Can't convert #{new_fragment.class} into String." end @fragment = new_fragment ? new_fragment.to_str : nil # Reset dependent values remove_instance_variable(:@normalized_fragment) if defined?(@normalized_fragment) remove_composite_values # Ensure we haven't created an invalid URI validate() end
[ "def", "fragment", "=", "(", "new_fragment", ")", "if", "new_fragment", "&&", "!", "new_fragment", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{new_fragment.class} into String.\"", "end", "@fragment", "=", "new_fragment", "?", "new_fragment", ".", "to_str", ":", "nil", "# Reset dependent values", "remove_instance_variable", "(", ":@normalized_fragment", ")", "if", "defined?", "(", "@normalized_fragment", ")", "remove_composite_values", "# Ensure we haven't created an invalid URI", "validate", "(", ")", "end" ]
Sets the fragment component for this URI. @param [String, #to_str] new_fragment The new fragment component.
[ "Sets", "the", "fragment", "component", "for", "this", "URI", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1809-L1821
12,862
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.join
def join(uri) if !uri.respond_to?(:to_str) raise TypeError, "Can't convert #{uri.class} into String." end if !uri.kind_of?(URI) # Otherwise, convert to a String, then parse. uri = URI.parse(uri.to_str) end if uri.to_s.empty? return self.dup end joined_scheme = nil joined_user = nil joined_password = nil joined_host = nil joined_port = nil joined_path = nil joined_query = nil joined_fragment = nil # Section 5.2.2 of RFC 3986 if uri.scheme != nil joined_scheme = uri.scheme joined_user = uri.user joined_password = uri.password joined_host = uri.host joined_port = uri.port joined_path = URI.normalize_path(uri.path) joined_query = uri.query else if uri.authority != nil joined_user = uri.user joined_password = uri.password joined_host = uri.host joined_port = uri.port joined_path = URI.normalize_path(uri.path) joined_query = uri.query else if uri.path == nil || uri.path.empty? joined_path = self.path if uri.query != nil joined_query = uri.query else joined_query = self.query end else if uri.path[0..0] == SLASH joined_path = URI.normalize_path(uri.path) else base_path = self.path.dup base_path = EMPTY_STR if base_path == nil base_path = URI.normalize_path(base_path) # Section 5.2.3 of RFC 3986 # # Removes the right-most path segment from the base path. if base_path =~ /\// base_path.sub!(/\/[^\/]+$/, SLASH) else base_path = EMPTY_STR end # If the base path is empty and an authority segment has been # defined, use a base path of SLASH if base_path.empty? && self.authority != nil base_path = SLASH end joined_path = URI.normalize_path(base_path + uri.path) end joined_query = uri.query end joined_user = self.user joined_password = self.password joined_host = self.host joined_port = self.port end joined_scheme = self.scheme end joined_fragment = uri.fragment return self.class.new( :scheme => joined_scheme, :user => joined_user, :password => joined_password, :host => joined_host, :port => joined_port, :path => joined_path, :query => joined_query, :fragment => joined_fragment ) end
ruby
def join(uri) if !uri.respond_to?(:to_str) raise TypeError, "Can't convert #{uri.class} into String." end if !uri.kind_of?(URI) # Otherwise, convert to a String, then parse. uri = URI.parse(uri.to_str) end if uri.to_s.empty? return self.dup end joined_scheme = nil joined_user = nil joined_password = nil joined_host = nil joined_port = nil joined_path = nil joined_query = nil joined_fragment = nil # Section 5.2.2 of RFC 3986 if uri.scheme != nil joined_scheme = uri.scheme joined_user = uri.user joined_password = uri.password joined_host = uri.host joined_port = uri.port joined_path = URI.normalize_path(uri.path) joined_query = uri.query else if uri.authority != nil joined_user = uri.user joined_password = uri.password joined_host = uri.host joined_port = uri.port joined_path = URI.normalize_path(uri.path) joined_query = uri.query else if uri.path == nil || uri.path.empty? joined_path = self.path if uri.query != nil joined_query = uri.query else joined_query = self.query end else if uri.path[0..0] == SLASH joined_path = URI.normalize_path(uri.path) else base_path = self.path.dup base_path = EMPTY_STR if base_path == nil base_path = URI.normalize_path(base_path) # Section 5.2.3 of RFC 3986 # # Removes the right-most path segment from the base path. if base_path =~ /\// base_path.sub!(/\/[^\/]+$/, SLASH) else base_path = EMPTY_STR end # If the base path is empty and an authority segment has been # defined, use a base path of SLASH if base_path.empty? && self.authority != nil base_path = SLASH end joined_path = URI.normalize_path(base_path + uri.path) end joined_query = uri.query end joined_user = self.user joined_password = self.password joined_host = self.host joined_port = self.port end joined_scheme = self.scheme end joined_fragment = uri.fragment return self.class.new( :scheme => joined_scheme, :user => joined_user, :password => joined_password, :host => joined_host, :port => joined_port, :path => joined_path, :query => joined_query, :fragment => joined_fragment ) end
[ "def", "join", "(", "uri", ")", "if", "!", "uri", ".", "respond_to?", "(", ":to_str", ")", "raise", "TypeError", ",", "\"Can't convert #{uri.class} into String.\"", "end", "if", "!", "uri", ".", "kind_of?", "(", "URI", ")", "# Otherwise, convert to a String, then parse.", "uri", "=", "URI", ".", "parse", "(", "uri", ".", "to_str", ")", "end", "if", "uri", ".", "to_s", ".", "empty?", "return", "self", ".", "dup", "end", "joined_scheme", "=", "nil", "joined_user", "=", "nil", "joined_password", "=", "nil", "joined_host", "=", "nil", "joined_port", "=", "nil", "joined_path", "=", "nil", "joined_query", "=", "nil", "joined_fragment", "=", "nil", "# Section 5.2.2 of RFC 3986", "if", "uri", ".", "scheme", "!=", "nil", "joined_scheme", "=", "uri", ".", "scheme", "joined_user", "=", "uri", ".", "user", "joined_password", "=", "uri", ".", "password", "joined_host", "=", "uri", ".", "host", "joined_port", "=", "uri", ".", "port", "joined_path", "=", "URI", ".", "normalize_path", "(", "uri", ".", "path", ")", "joined_query", "=", "uri", ".", "query", "else", "if", "uri", ".", "authority", "!=", "nil", "joined_user", "=", "uri", ".", "user", "joined_password", "=", "uri", ".", "password", "joined_host", "=", "uri", ".", "host", "joined_port", "=", "uri", ".", "port", "joined_path", "=", "URI", ".", "normalize_path", "(", "uri", ".", "path", ")", "joined_query", "=", "uri", ".", "query", "else", "if", "uri", ".", "path", "==", "nil", "||", "uri", ".", "path", ".", "empty?", "joined_path", "=", "self", ".", "path", "if", "uri", ".", "query", "!=", "nil", "joined_query", "=", "uri", ".", "query", "else", "joined_query", "=", "self", ".", "query", "end", "else", "if", "uri", ".", "path", "[", "0", "..", "0", "]", "==", "SLASH", "joined_path", "=", "URI", ".", "normalize_path", "(", "uri", ".", "path", ")", "else", "base_path", "=", "self", ".", "path", ".", "dup", "base_path", "=", "EMPTY_STR", "if", "base_path", "==", "nil", "base_path", "=", "URI", ".", "normalize_path", "(", "base_path", ")", "# Section 5.2.3 of RFC 3986", "#", "# Removes the right-most path segment from the base path.", "if", "base_path", "=~", "/", "\\/", "/", "base_path", ".", "sub!", "(", "/", "\\/", "\\/", "/", ",", "SLASH", ")", "else", "base_path", "=", "EMPTY_STR", "end", "# If the base path is empty and an authority segment has been", "# defined, use a base path of SLASH", "if", "base_path", ".", "empty?", "&&", "self", ".", "authority", "!=", "nil", "base_path", "=", "SLASH", "end", "joined_path", "=", "URI", ".", "normalize_path", "(", "base_path", "+", "uri", ".", "path", ")", "end", "joined_query", "=", "uri", ".", "query", "end", "joined_user", "=", "self", ".", "user", "joined_password", "=", "self", ".", "password", "joined_host", "=", "self", ".", "host", "joined_port", "=", "self", ".", "port", "end", "joined_scheme", "=", "self", ".", "scheme", "end", "joined_fragment", "=", "uri", ".", "fragment", "return", "self", ".", "class", ".", "new", "(", ":scheme", "=>", "joined_scheme", ",", ":user", "=>", "joined_user", ",", ":password", "=>", "joined_password", ",", ":host", "=>", "joined_host", ",", ":port", "=>", "joined_port", ",", ":path", "=>", "joined_path", ",", ":query", "=>", "joined_query", ",", ":fragment", "=>", "joined_fragment", ")", "end" ]
Joins two URIs together. @param [String, Addressable::URI, #to_str] The URI to join with. @return [Addressable::URI] The joined URI.
[ "Joins", "two", "URIs", "together", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L1863-L1955
12,863
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.normalize
def normalize # This is a special exception for the frequently misused feed # URI scheme. if normalized_scheme == "feed" if self.to_s =~ /^feed:\/*http:\/*/ return URI.parse( self.to_s[/^feed:\/*(http:\/*.*)/, 1] ).normalize end end return self.class.new( :scheme => normalized_scheme, :authority => normalized_authority, :path => normalized_path, :query => normalized_query, :fragment => normalized_fragment ) end
ruby
def normalize # This is a special exception for the frequently misused feed # URI scheme. if normalized_scheme == "feed" if self.to_s =~ /^feed:\/*http:\/*/ return URI.parse( self.to_s[/^feed:\/*(http:\/*.*)/, 1] ).normalize end end return self.class.new( :scheme => normalized_scheme, :authority => normalized_authority, :path => normalized_path, :query => normalized_query, :fragment => normalized_fragment ) end
[ "def", "normalize", "# This is a special exception for the frequently misused feed", "# URI scheme.", "if", "normalized_scheme", "==", "\"feed\"", "if", "self", ".", "to_s", "=~", "/", "\\/", "\\/", "/", "return", "URI", ".", "parse", "(", "self", ".", "to_s", "[", "/", "\\/", "\\/", "/", ",", "1", "]", ")", ".", "normalize", "end", "end", "return", "self", ".", "class", ".", "new", "(", ":scheme", "=>", "normalized_scheme", ",", ":authority", "=>", "normalized_authority", ",", ":path", "=>", "normalized_path", ",", ":query", "=>", "normalized_query", ",", ":fragment", "=>", "normalized_fragment", ")", "end" ]
Returns a normalized URI object. NOTE: This method does not attempt to fully conform to specifications. It exists largely to correct other people's failures to read the specifications, and also to deal with caching issues since several different URIs may represent the same resource and should not be cached multiple times. @return [Addressable::URI] The normalized URI.
[ "Returns", "a", "normalized", "URI", "object", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L2138-L2156
12,864
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.defer_validation
def defer_validation(&block) raise LocalJumpError, "No block given." unless block @validation_deferred = true block.call() @validation_deferred = false validate return nil end
ruby
def defer_validation(&block) raise LocalJumpError, "No block given." unless block @validation_deferred = true block.call() @validation_deferred = false validate return nil end
[ "def", "defer_validation", "(", "&", "block", ")", "raise", "LocalJumpError", ",", "\"No block given.\"", "unless", "block", "@validation_deferred", "=", "true", "block", ".", "call", "(", ")", "@validation_deferred", "=", "false", "validate", "return", "nil", "end" ]
This method allows you to make several changes to a URI simultaneously, which separately would cause validation errors, but in conjunction, are valid. The URI will be revalidated as soon as the entire block has been executed. @param [Proc] block A set of operations to perform on a given URI.
[ "This", "method", "allows", "you", "to", "make", "several", "changes", "to", "a", "URI", "simultaneously", "which", "separately", "would", "cause", "validation", "errors", "but", "in", "conjunction", "are", "valid", ".", "The", "URI", "will", "be", "revalidated", "as", "soon", "as", "the", "entire", "block", "has", "been", "executed", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L2370-L2377
12,865
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.validate
def validate return if !!@validation_deferred if self.scheme != nil && self.ip_based? && (self.host == nil || self.host.empty?) && (self.path == nil || self.path.empty?) raise InvalidURIError, "Absolute URI missing hierarchical segment: '#{self.to_s}'" end if self.host == nil if self.port != nil || self.user != nil || self.password != nil raise InvalidURIError, "Hostname not supplied: '#{self.to_s}'" end end if self.path != nil && !self.path.empty? && self.path[0..0] != SLASH && self.authority != nil raise InvalidURIError, "Cannot have a relative path with an authority set: '#{self.to_s}'" end if self.path != nil && !self.path.empty? && self.path[0..1] == SLASH + SLASH && self.authority == nil raise InvalidURIError, "Cannot have a path with two leading slashes " + "without an authority set: '#{self.to_s}'" end unreserved = CharacterClasses::UNRESERVED sub_delims = CharacterClasses::SUB_DELIMS if !self.host.nil? && (self.host =~ /[<>{}\/\\\?\#\@"[[:space:]]]/ || (self.host[/^\[(.*)\]$/, 1] != nil && self.host[/^\[(.*)\]$/, 1] !~ Regexp.new("^[#{unreserved}#{sub_delims}:]*$"))) raise InvalidURIError, "Invalid character in host: '#{self.host.to_s}'" end return nil end
ruby
def validate return if !!@validation_deferred if self.scheme != nil && self.ip_based? && (self.host == nil || self.host.empty?) && (self.path == nil || self.path.empty?) raise InvalidURIError, "Absolute URI missing hierarchical segment: '#{self.to_s}'" end if self.host == nil if self.port != nil || self.user != nil || self.password != nil raise InvalidURIError, "Hostname not supplied: '#{self.to_s}'" end end if self.path != nil && !self.path.empty? && self.path[0..0] != SLASH && self.authority != nil raise InvalidURIError, "Cannot have a relative path with an authority set: '#{self.to_s}'" end if self.path != nil && !self.path.empty? && self.path[0..1] == SLASH + SLASH && self.authority == nil raise InvalidURIError, "Cannot have a path with two leading slashes " + "without an authority set: '#{self.to_s}'" end unreserved = CharacterClasses::UNRESERVED sub_delims = CharacterClasses::SUB_DELIMS if !self.host.nil? && (self.host =~ /[<>{}\/\\\?\#\@"[[:space:]]]/ || (self.host[/^\[(.*)\]$/, 1] != nil && self.host[/^\[(.*)\]$/, 1] !~ Regexp.new("^[#{unreserved}#{sub_delims}:]*$"))) raise InvalidURIError, "Invalid character in host: '#{self.host.to_s}'" end return nil end
[ "def", "validate", "return", "if", "!", "!", "@validation_deferred", "if", "self", ".", "scheme", "!=", "nil", "&&", "self", ".", "ip_based?", "&&", "(", "self", ".", "host", "==", "nil", "||", "self", ".", "host", ".", "empty?", ")", "&&", "(", "self", ".", "path", "==", "nil", "||", "self", ".", "path", ".", "empty?", ")", "raise", "InvalidURIError", ",", "\"Absolute URI missing hierarchical segment: '#{self.to_s}'\"", "end", "if", "self", ".", "host", "==", "nil", "if", "self", ".", "port", "!=", "nil", "||", "self", ".", "user", "!=", "nil", "||", "self", ".", "password", "!=", "nil", "raise", "InvalidURIError", ",", "\"Hostname not supplied: '#{self.to_s}'\"", "end", "end", "if", "self", ".", "path", "!=", "nil", "&&", "!", "self", ".", "path", ".", "empty?", "&&", "self", ".", "path", "[", "0", "..", "0", "]", "!=", "SLASH", "&&", "self", ".", "authority", "!=", "nil", "raise", "InvalidURIError", ",", "\"Cannot have a relative path with an authority set: '#{self.to_s}'\"", "end", "if", "self", ".", "path", "!=", "nil", "&&", "!", "self", ".", "path", ".", "empty?", "&&", "self", ".", "path", "[", "0", "..", "1", "]", "==", "SLASH", "+", "SLASH", "&&", "self", ".", "authority", "==", "nil", "raise", "InvalidURIError", ",", "\"Cannot have a path with two leading slashes \"", "+", "\"without an authority set: '#{self.to_s}'\"", "end", "unreserved", "=", "CharacterClasses", "::", "UNRESERVED", "sub_delims", "=", "CharacterClasses", "::", "SUB_DELIMS", "if", "!", "self", ".", "host", ".", "nil?", "&&", "(", "self", ".", "host", "=~", "/", "\\/", "\\\\", "\\?", "\\#", "\\@", "/", "||", "(", "self", ".", "host", "[", "/", "\\[", "\\]", "/", ",", "1", "]", "!=", "nil", "&&", "self", ".", "host", "[", "/", "\\[", "\\]", "/", ",", "1", "]", "!~", "Regexp", ".", "new", "(", "\"^[#{unreserved}#{sub_delims}:]*$\"", ")", ")", ")", "raise", "InvalidURIError", ",", "\"Invalid character in host: '#{self.host.to_s}'\"", "end", "return", "nil", "end" ]
Ensures that the URI is valid.
[ "Ensures", "that", "the", "URI", "is", "valid", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L2425-L2459
12,866
sporkmonger/addressable
lib/addressable/uri.rb
Addressable.URI.replace_self
def replace_self(uri) # Reset dependent values instance_variables.each do |var| if instance_variable_defined?(var) && var != :@validation_deferred remove_instance_variable(var) end end @scheme = uri.scheme @user = uri.user @password = uri.password @host = uri.host @port = uri.port @path = uri.path @query = uri.query @fragment = uri.fragment return self end
ruby
def replace_self(uri) # Reset dependent values instance_variables.each do |var| if instance_variable_defined?(var) && var != :@validation_deferred remove_instance_variable(var) end end @scheme = uri.scheme @user = uri.user @password = uri.password @host = uri.host @port = uri.port @path = uri.path @query = uri.query @fragment = uri.fragment return self end
[ "def", "replace_self", "(", "uri", ")", "# Reset dependent values", "instance_variables", ".", "each", "do", "|", "var", "|", "if", "instance_variable_defined?", "(", "var", ")", "&&", "var", "!=", ":@validation_deferred", "remove_instance_variable", "(", "var", ")", "end", "end", "@scheme", "=", "uri", ".", "scheme", "@user", "=", "uri", ".", "user", "@password", "=", "uri", ".", "password", "@host", "=", "uri", ".", "host", "@port", "=", "uri", ".", "port", "@path", "=", "uri", ".", "path", "@query", "=", "uri", ".", "query", "@fragment", "=", "uri", ".", "fragment", "return", "self", "end" ]
Replaces the internal state of self with the specified URI's state. Used in destructive operations to avoid massive code repetition. @param [Addressable::URI] uri The URI to replace <code>self</code> with. @return [Addressable::URI] <code>self</code>.
[ "Replaces", "the", "internal", "state", "of", "self", "with", "the", "specified", "URI", "s", "state", ".", "Used", "in", "destructive", "operations", "to", "avoid", "massive", "code", "repetition", "." ]
5894c95a7768435cb46d1355954611dbd194832e
https://github.com/sporkmonger/addressable/blob/5894c95a7768435cb46d1355954611dbd194832e/lib/addressable/uri.rb#L2468-L2485
12,867
Dynamoid/dynamoid
lib/dynamoid/fields.rb
Dynamoid.Fields.write_attribute
def write_attribute(name, value) name = name.to_sym if association = @associations[name] association.reset end @attributes_before_type_cast[name] = value value_casted = TypeCasting.cast_field(value, self.class.attributes[name]) attributes[name] = value_casted end
ruby
def write_attribute(name, value) name = name.to_sym if association = @associations[name] association.reset end @attributes_before_type_cast[name] = value value_casted = TypeCasting.cast_field(value, self.class.attributes[name]) attributes[name] = value_casted end
[ "def", "write_attribute", "(", "name", ",", "value", ")", "name", "=", "name", ".", "to_sym", "if", "association", "=", "@associations", "[", "name", "]", "association", ".", "reset", "end", "@attributes_before_type_cast", "[", "name", "]", "=", "value", "value_casted", "=", "TypeCasting", ".", "cast_field", "(", "value", ",", "self", ".", "class", ".", "attributes", "[", "name", "]", ")", "attributes", "[", "name", "]", "=", "value_casted", "end" ]
Write an attribute on the object. Also marks the previous value as dirty. @param [Symbol] name the name of the field @param [Object] value the value to assign to that field @since 0.2.0
[ "Write", "an", "attribute", "on", "the", "object", ".", "Also", "marks", "the", "previous", "value", "as", "dirty", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/fields.rb#L117-L128
12,868
Dynamoid/dynamoid
lib/dynamoid/fields.rb
Dynamoid.Fields.set_created_at
def set_created_at self.created_at ||= DateTime.now.in_time_zone(Time.zone) if Dynamoid::Config.timestamps end
ruby
def set_created_at self.created_at ||= DateTime.now.in_time_zone(Time.zone) if Dynamoid::Config.timestamps end
[ "def", "set_created_at", "self", ".", "created_at", "||=", "DateTime", ".", "now", ".", "in_time_zone", "(", "Time", ".", "zone", ")", "if", "Dynamoid", "::", "Config", ".", "timestamps", "end" ]
Automatically called during the created callback to set the created_at time. @since 0.2.0
[ "Automatically", "called", "during", "the", "created", "callback", "to", "set", "the", "created_at", "time", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/fields.rb#L160-L162
12,869
Dynamoid/dynamoid
lib/dynamoid/fields.rb
Dynamoid.Fields.set_updated_at
def set_updated_at if Dynamoid::Config.timestamps && !updated_at_changed? self.updated_at = DateTime.now.in_time_zone(Time.zone) end end
ruby
def set_updated_at if Dynamoid::Config.timestamps && !updated_at_changed? self.updated_at = DateTime.now.in_time_zone(Time.zone) end end
[ "def", "set_updated_at", "if", "Dynamoid", "::", "Config", ".", "timestamps", "&&", "!", "updated_at_changed?", "self", ".", "updated_at", "=", "DateTime", ".", "now", ".", "in_time_zone", "(", "Time", ".", "zone", ")", "end", "end" ]
Automatically called during the save callback to set the updated_at time. @since 0.2.0
[ "Automatically", "called", "during", "the", "save", "callback", "to", "set", "the", "updated_at", "time", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/fields.rb#L167-L171
12,870
Dynamoid/dynamoid
lib/dynamoid/document.rb
Dynamoid.Document.reload
def reload options = { consistent_read: true } if self.class.range_key options[:range_key] = range_value end self.attributes = self.class.find(hash_key, options).attributes @associations.values.each(&:reset) self end
ruby
def reload options = { consistent_read: true } if self.class.range_key options[:range_key] = range_value end self.attributes = self.class.find(hash_key, options).attributes @associations.values.each(&:reset) self end
[ "def", "reload", "options", "=", "{", "consistent_read", ":", "true", "}", "if", "self", ".", "class", ".", "range_key", "options", "[", ":range_key", "]", "=", "range_value", "end", "self", ".", "attributes", "=", "self", ".", "class", ".", "find", "(", "hash_key", ",", "options", ")", ".", "attributes", "@associations", ".", "values", ".", "each", "(", ":reset", ")", "self", "end" ]
An object is equal to another object if their ids are equal. @since 0.2.0 Reload an object from the database -- if you suspect the object has changed in the datastore and you need those changes to be reflected immediately, you would call this method. This is a consistent read. @return [Dynamoid::Document] the document this method was called on @since 0.2.0
[ "An", "object", "is", "equal", "to", "another", "object", "if", "their", "ids", "are", "equal", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/document.rb#L374-L384
12,871
Dynamoid/dynamoid
lib/dynamoid/document.rb
Dynamoid.Document.evaluate_default_value
def evaluate_default_value(val) if val.respond_to?(:call) val.call elsif val.duplicable? val.dup else val end end
ruby
def evaluate_default_value(val) if val.respond_to?(:call) val.call elsif val.duplicable? val.dup else val end end
[ "def", "evaluate_default_value", "(", "val", ")", "if", "val", ".", "respond_to?", "(", ":call", ")", "val", ".", "call", "elsif", "val", ".", "duplicable?", "val", ".", "dup", "else", "val", "end", "end" ]
Evaluates the default value given, this is used by undump when determining the value of the default given for a field options. @param [Object] :value the attribute's default value
[ "Evaluates", "the", "default", "value", "given", "this", "is", "used", "by", "undump", "when", "determining", "the", "value", "of", "the", "default", "given", "for", "a", "field", "options", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/document.rb#L420-L428
12,872
Dynamoid/dynamoid
lib/dynamoid/persistence.rb
Dynamoid.Persistence.touch
def touch(name = nil) now = DateTime.now self.updated_at = now attributes[name] = now if name save end
ruby
def touch(name = nil) now = DateTime.now self.updated_at = now attributes[name] = now if name save end
[ "def", "touch", "(", "name", "=", "nil", ")", "now", "=", "DateTime", ".", "now", "self", ".", "updated_at", "=", "now", "attributes", "[", "name", "]", "=", "now", "if", "name", "save", "end" ]
Set updated_at and any passed in field to current DateTime. Useful for things like last_login_at, etc.
[ "Set", "updated_at", "and", "any", "passed", "in", "field", "to", "current", "DateTime", ".", "Useful", "for", "things", "like", "last_login_at", "etc", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/persistence.rb#L123-L128
12,873
Dynamoid/dynamoid
lib/dynamoid/persistence.rb
Dynamoid.Persistence.save
def save(_options = {}) self.class.create_table if new_record? conditions = { unless_exists: [self.class.hash_key] } conditions[:unless_exists] << range_key if range_key run_callbacks(:create) { persist(conditions) } else persist end end
ruby
def save(_options = {}) self.class.create_table if new_record? conditions = { unless_exists: [self.class.hash_key] } conditions[:unless_exists] << range_key if range_key run_callbacks(:create) { persist(conditions) } else persist end end
[ "def", "save", "(", "_options", "=", "{", "}", ")", "self", ".", "class", ".", "create_table", "if", "new_record?", "conditions", "=", "{", "unless_exists", ":", "[", "self", ".", "class", ".", "hash_key", "]", "}", "conditions", "[", ":unless_exists", "]", "<<", "range_key", "if", "range_key", "run_callbacks", "(", ":create", ")", "{", "persist", "(", "conditions", ")", "}", "else", "persist", "end", "end" ]
Run the callbacks and then persist this object in the datastore. @since 0.2.0
[ "Run", "the", "callbacks", "and", "then", "persist", "this", "object", "in", "the", "datastore", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/persistence.rb#L140-L151
12,874
Dynamoid/dynamoid
lib/dynamoid/persistence.rb
Dynamoid.Persistence.update_attributes
def update_attributes(attributes) attributes.each { |attribute, value| write_attribute(attribute, value) } save end
ruby
def update_attributes(attributes) attributes.each { |attribute, value| write_attribute(attribute, value) } save end
[ "def", "update_attributes", "(", "attributes", ")", "attributes", ".", "each", "{", "|", "attribute", ",", "value", "|", "write_attribute", "(", "attribute", ",", "value", ")", "}", "save", "end" ]
Updates multiple attributes at once, saving the object once the updates are complete. @param [Hash] attributes a hash of attributes to update @since 0.2.0
[ "Updates", "multiple", "attributes", "at", "once", "saving", "the", "object", "once", "the", "updates", "are", "complete", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/persistence.rb#L158-L161
12,875
Dynamoid/dynamoid
lib/dynamoid/persistence.rb
Dynamoid.Persistence.delete
def delete options = range_key ? { range_key: Dumping.dump_field(read_attribute(range_key), self.class.attributes[range_key]) } : {} # Add an optimistic locking check if the lock_version column exists if self.class.attributes[:lock_version] conditions = { if: {} } conditions[:if][:lock_version] = if changes[:lock_version].nil? lock_version else changes[:lock_version][0] end options[:conditions] = conditions end Dynamoid.adapter.delete(self.class.table_name, hash_key, options) rescue Dynamoid::Errors::ConditionalCheckFailedException raise Dynamoid::Errors::StaleObjectError.new(self, 'delete') end
ruby
def delete options = range_key ? { range_key: Dumping.dump_field(read_attribute(range_key), self.class.attributes[range_key]) } : {} # Add an optimistic locking check if the lock_version column exists if self.class.attributes[:lock_version] conditions = { if: {} } conditions[:if][:lock_version] = if changes[:lock_version].nil? lock_version else changes[:lock_version][0] end options[:conditions] = conditions end Dynamoid.adapter.delete(self.class.table_name, hash_key, options) rescue Dynamoid::Errors::ConditionalCheckFailedException raise Dynamoid::Errors::StaleObjectError.new(self, 'delete') end
[ "def", "delete", "options", "=", "range_key", "?", "{", "range_key", ":", "Dumping", ".", "dump_field", "(", "read_attribute", "(", "range_key", ")", ",", "self", ".", "class", ".", "attributes", "[", "range_key", "]", ")", "}", ":", "{", "}", "# Add an optimistic locking check if the lock_version column exists", "if", "self", ".", "class", ".", "attributes", "[", ":lock_version", "]", "conditions", "=", "{", "if", ":", "{", "}", "}", "conditions", "[", ":if", "]", "[", ":lock_version", "]", "=", "if", "changes", "[", ":lock_version", "]", ".", "nil?", "lock_version", "else", "changes", "[", ":lock_version", "]", "[", "0", "]", "end", "options", "[", ":conditions", "]", "=", "conditions", "end", "Dynamoid", ".", "adapter", ".", "delete", "(", "self", ".", "class", ".", "table_name", ",", "hash_key", ",", "options", ")", "rescue", "Dynamoid", "::", "Errors", "::", "ConditionalCheckFailedException", "raise", "Dynamoid", "::", "Errors", "::", "StaleObjectError", ".", "new", "(", "self", ",", "'delete'", ")", "end" ]
Delete this object from the datastore. @since 0.2.0
[ "Delete", "this", "object", "from", "the", "datastore", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/persistence.rb#L265-L282
12,876
Dynamoid/dynamoid
lib/dynamoid/persistence.rb
Dynamoid.Persistence.persist
def persist(conditions = nil) run_callbacks(:save) do self.hash_key = SecureRandom.uuid if hash_key.blank? # Add an exists check to prevent overwriting existing records with new ones if new_record? conditions ||= {} (conditions[:unless_exists] ||= []) << self.class.hash_key end # Add an optimistic locking check if the lock_version column exists if self.class.attributes[:lock_version] conditions ||= {} self.lock_version = (lock_version || 0) + 1 # Uses the original lock_version value from ActiveModel::Dirty in case user changed lock_version manually (conditions[:if] ||= {})[:lock_version] = changes[:lock_version][0] if changes[:lock_version][0] end attributes_dumped = Dumping.dump_attributes(attributes, self.class.attributes) begin Dynamoid.adapter.write(self.class.table_name, attributes_dumped, conditions) @new_record = false true rescue Dynamoid::Errors::ConditionalCheckFailedException => e if new_record? raise Dynamoid::Errors::RecordNotUnique.new(e, self) else raise Dynamoid::Errors::StaleObjectError.new(self, 'persist') end end end end
ruby
def persist(conditions = nil) run_callbacks(:save) do self.hash_key = SecureRandom.uuid if hash_key.blank? # Add an exists check to prevent overwriting existing records with new ones if new_record? conditions ||= {} (conditions[:unless_exists] ||= []) << self.class.hash_key end # Add an optimistic locking check if the lock_version column exists if self.class.attributes[:lock_version] conditions ||= {} self.lock_version = (lock_version || 0) + 1 # Uses the original lock_version value from ActiveModel::Dirty in case user changed lock_version manually (conditions[:if] ||= {})[:lock_version] = changes[:lock_version][0] if changes[:lock_version][0] end attributes_dumped = Dumping.dump_attributes(attributes, self.class.attributes) begin Dynamoid.adapter.write(self.class.table_name, attributes_dumped, conditions) @new_record = false true rescue Dynamoid::Errors::ConditionalCheckFailedException => e if new_record? raise Dynamoid::Errors::RecordNotUnique.new(e, self) else raise Dynamoid::Errors::StaleObjectError.new(self, 'persist') end end end end
[ "def", "persist", "(", "conditions", "=", "nil", ")", "run_callbacks", "(", ":save", ")", "do", "self", ".", "hash_key", "=", "SecureRandom", ".", "uuid", "if", "hash_key", ".", "blank?", "# Add an exists check to prevent overwriting existing records with new ones", "if", "new_record?", "conditions", "||=", "{", "}", "(", "conditions", "[", ":unless_exists", "]", "||=", "[", "]", ")", "<<", "self", ".", "class", ".", "hash_key", "end", "# Add an optimistic locking check if the lock_version column exists", "if", "self", ".", "class", ".", "attributes", "[", ":lock_version", "]", "conditions", "||=", "{", "}", "self", ".", "lock_version", "=", "(", "lock_version", "||", "0", ")", "+", "1", "# Uses the original lock_version value from ActiveModel::Dirty in case user changed lock_version manually", "(", "conditions", "[", ":if", "]", "||=", "{", "}", ")", "[", ":lock_version", "]", "=", "changes", "[", ":lock_version", "]", "[", "0", "]", "if", "changes", "[", ":lock_version", "]", "[", "0", "]", "end", "attributes_dumped", "=", "Dumping", ".", "dump_attributes", "(", "attributes", ",", "self", ".", "class", ".", "attributes", ")", "begin", "Dynamoid", ".", "adapter", ".", "write", "(", "self", ".", "class", ".", "table_name", ",", "attributes_dumped", ",", "conditions", ")", "@new_record", "=", "false", "true", "rescue", "Dynamoid", "::", "Errors", "::", "ConditionalCheckFailedException", "=>", "e", "if", "new_record?", "raise", "Dynamoid", "::", "Errors", "::", "RecordNotUnique", ".", "new", "(", "e", ",", "self", ")", "else", "raise", "Dynamoid", "::", "Errors", "::", "StaleObjectError", ".", "new", "(", "self", ",", "'persist'", ")", "end", "end", "end", "end" ]
Persist the object into the datastore. Assign it an id first if it doesn't have one. @since 0.2.0
[ "Persist", "the", "object", "into", "the", "datastore", ".", "Assign", "it", "an", "id", "first", "if", "it", "doesn", "t", "have", "one", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/persistence.rb#L289-L321
12,877
Dynamoid/dynamoid
lib/dynamoid/adapter.rb
Dynamoid.Adapter.adapter
def adapter unless @adapter_.value adapter = self.class.adapter_plugin_class.new adapter.connect! if adapter.respond_to?(:connect!) @adapter_.compare_and_set(nil, adapter) clear_cache! end @adapter_.value end
ruby
def adapter unless @adapter_.value adapter = self.class.adapter_plugin_class.new adapter.connect! if adapter.respond_to?(:connect!) @adapter_.compare_and_set(nil, adapter) clear_cache! end @adapter_.value end
[ "def", "adapter", "unless", "@adapter_", ".", "value", "adapter", "=", "self", ".", "class", ".", "adapter_plugin_class", ".", "new", "adapter", ".", "connect!", "if", "adapter", ".", "respond_to?", "(", ":connect!", ")", "@adapter_", ".", "compare_and_set", "(", "nil", ",", "adapter", ")", "clear_cache!", "end", "@adapter_", ".", "value", "end" ]
The actual adapter currently in use. @since 0.2.0
[ "The", "actual", "adapter", "currently", "in", "use", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/adapter.rb#L29-L37
12,878
Dynamoid/dynamoid
lib/dynamoid/adapter.rb
Dynamoid.Adapter.benchmark
def benchmark(method, *args) start = Time.now result = yield Dynamoid.logger.debug "(#{((Time.now - start) * 1000.0).round(2)} ms) #{method.to_s.split('_').collect(&:upcase).join(' ')}#{" - #{args.inspect}" unless args.nil? || args.empty?}" result end
ruby
def benchmark(method, *args) start = Time.now result = yield Dynamoid.logger.debug "(#{((Time.now - start) * 1000.0).round(2)} ms) #{method.to_s.split('_').collect(&:upcase).join(' ')}#{" - #{args.inspect}" unless args.nil? || args.empty?}" result end
[ "def", "benchmark", "(", "method", ",", "*", "args", ")", "start", "=", "Time", ".", "now", "result", "=", "yield", "Dynamoid", ".", "logger", ".", "debug", "\"(#{((Time.now - start) * 1000.0).round(2)} ms) #{method.to_s.split('_').collect(&:upcase).join(' ')}#{\" - #{args.inspect}\" unless args.nil? || args.empty?}\"", "result", "end" ]
Shows how long it takes a method to run on the adapter. Useful for generating logged output. @param [Symbol] method the name of the method to appear in the log @param [Array] args the arguments to the method to appear in the log @yield the actual code to benchmark @return the result of the yield @since 0.2.0
[ "Shows", "how", "long", "it", "takes", "a", "method", "to", "run", "on", "the", "adapter", ".", "Useful", "for", "generating", "logged", "output", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/adapter.rb#L52-L57
12,879
Dynamoid/dynamoid
lib/dynamoid/adapter.rb
Dynamoid.Adapter.read
def read(table, ids, options = {}, &blk) if ids.respond_to?(:each) batch_get_item({ table => ids }, options, &blk) else get_item(table, ids, options) end end
ruby
def read(table, ids, options = {}, &blk) if ids.respond_to?(:each) batch_get_item({ table => ids }, options, &blk) else get_item(table, ids, options) end end
[ "def", "read", "(", "table", ",", "ids", ",", "options", "=", "{", "}", ",", "&", "blk", ")", "if", "ids", ".", "respond_to?", "(", ":each", ")", "batch_get_item", "(", "{", "table", "=>", "ids", "}", ",", "options", ",", "blk", ")", "else", "get_item", "(", "table", ",", "ids", ",", "options", ")", "end", "end" ]
Read one or many keys from the selected table. This method intelligently calls batch_get or get on the underlying adapter depending on whether ids is a range or a single key. If a range key is present, it will also interpolate that into the ids so that the batch get will acquire the correct record. @param [String] table the name of the table to write the object to @param [Array] ids to fetch, can also be a string of just one id @param [Hash] options: Passed to the underlying query. The :range_key option is required whenever the table has a range key, unless multiple ids are passed in. @since 0.2.0
[ "Read", "one", "or", "many", "keys", "from", "the", "selected", "table", ".", "This", "method", "intelligently", "calls", "batch_get", "or", "get", "on", "the", "underlying", "adapter", "depending", "on", "whether", "ids", "is", "a", "range", "or", "a", "single", "key", ".", "If", "a", "range", "key", "is", "present", "it", "will", "also", "interpolate", "that", "into", "the", "ids", "so", "that", "the", "batch", "get", "will", "acquire", "the", "correct", "record", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/adapter.rb#L84-L90
12,880
Dynamoid/dynamoid
lib/dynamoid/adapter.rb
Dynamoid.Adapter.delete
def delete(table, ids, options = {}) range_key = options[:range_key] # array of range keys that matches the ids passed in if ids.respond_to?(:each) ids = if range_key.respond_to?(:each) # turn ids into array of arrays each element being hash_key, range_key ids.each_with_index.map { |id, i| [id, range_key[i]] } else range_key ? ids.map { |id| [id, range_key] } : ids end batch_delete_item(table => ids) else delete_item(table, ids, options) end end
ruby
def delete(table, ids, options = {}) range_key = options[:range_key] # array of range keys that matches the ids passed in if ids.respond_to?(:each) ids = if range_key.respond_to?(:each) # turn ids into array of arrays each element being hash_key, range_key ids.each_with_index.map { |id, i| [id, range_key[i]] } else range_key ? ids.map { |id| [id, range_key] } : ids end batch_delete_item(table => ids) else delete_item(table, ids, options) end end
[ "def", "delete", "(", "table", ",", "ids", ",", "options", "=", "{", "}", ")", "range_key", "=", "options", "[", ":range_key", "]", "# array of range keys that matches the ids passed in", "if", "ids", ".", "respond_to?", "(", ":each", ")", "ids", "=", "if", "range_key", ".", "respond_to?", "(", ":each", ")", "# turn ids into array of arrays each element being hash_key, range_key", "ids", ".", "each_with_index", ".", "map", "{", "|", "id", ",", "i", "|", "[", "id", ",", "range_key", "[", "i", "]", "]", "}", "else", "range_key", "?", "ids", ".", "map", "{", "|", "id", "|", "[", "id", ",", "range_key", "]", "}", ":", "ids", "end", "batch_delete_item", "(", "table", "=>", "ids", ")", "else", "delete_item", "(", "table", ",", "ids", ",", "options", ")", "end", "end" ]
Delete an item from a table. @param [String] table the name of the table to write the object to @param [Array] ids to delete, can also be a string of just one id @param [Array] range_key of the record to delete, can also be a string of just one range_key
[ "Delete", "an", "item", "from", "a", "table", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/adapter.rb#L98-L112
12,881
Dynamoid/dynamoid
lib/dynamoid/adapter.rb
Dynamoid.Adapter.scan
def scan(table, query = {}, opts = {}) benchmark('Scan', table, query) { adapter.scan(table, query, opts) } end
ruby
def scan(table, query = {}, opts = {}) benchmark('Scan', table, query) { adapter.scan(table, query, opts) } end
[ "def", "scan", "(", "table", ",", "query", "=", "{", "}", ",", "opts", "=", "{", "}", ")", "benchmark", "(", "'Scan'", ",", "table", ",", "query", ")", "{", "adapter", ".", "scan", "(", "table", ",", "query", ",", "opts", ")", "}", "end" ]
Scans a table. Generally quite slow; try to avoid using scan if at all possible. @param [String] table the name of the table to write the object to @param [Hash] scan_hash a hash of attributes: matching records will be returned by the scan @since 0.2.0
[ "Scans", "a", "table", ".", "Generally", "quite", "slow", ";", "try", "to", "avoid", "using", "scan", "if", "at", "all", "possible", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/adapter.rb#L120-L122
12,882
Dynamoid/dynamoid
lib/dynamoid/adapter.rb
Dynamoid.Adapter.method_missing
def method_missing(method, *args, &block) return benchmark(method, *args) { adapter.send(method, *args, &block) } if adapter.respond_to?(method) super end
ruby
def method_missing(method, *args, &block) return benchmark(method, *args) { adapter.send(method, *args, &block) } if adapter.respond_to?(method) super end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "return", "benchmark", "(", "method", ",", "args", ")", "{", "adapter", ".", "send", "(", "method", ",", "args", ",", "block", ")", "}", "if", "adapter", ".", "respond_to?", "(", "method", ")", "super", "end" ]
Delegate all methods that aren't defind here to the underlying adapter. @since 0.2.0
[ "Delegate", "all", "methods", "that", "aren", "t", "defind", "here", "to", "the", "underlying", "adapter", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/adapter.rb#L156-L160
12,883
Dynamoid/dynamoid
lib/dynamoid/config.rb
Dynamoid.Config.logger=
def logger=(logger) case logger when false, nil then @logger = NullLogger.new when true then @logger = default_logger else @logger = logger if logger.respond_to?(:info) end end
ruby
def logger=(logger) case logger when false, nil then @logger = NullLogger.new when true then @logger = default_logger else @logger = logger if logger.respond_to?(:info) end end
[ "def", "logger", "=", "(", "logger", ")", "case", "logger", "when", "false", ",", "nil", "then", "@logger", "=", "NullLogger", ".", "new", "when", "true", "then", "@logger", "=", "default_logger", "else", "@logger", "=", "logger", "if", "logger", ".", "respond_to?", "(", ":info", ")", "end", "end" ]
If you want to, set the logger manually to any output you'd like. Or pass false or nil to disable logging entirely. @since 0.2.0
[ "If", "you", "want", "to", "set", "the", "logger", "manually", "to", "any", "output", "you", "d", "like", ".", "Or", "pass", "false", "or", "nil", "to", "disable", "logging", "entirely", "." ]
9e3d006b039e45877b003564ded65509b10b6354
https://github.com/Dynamoid/dynamoid/blob/9e3d006b039e45877b003564ded65509b10b6354/lib/dynamoid/config.rb#L67-L74
12,884
boazsegev/combine_pdf
lib/combine_pdf/renderer.rb
CombinePDF.Renderer.object_to_pdf
def object_to_pdf(object) if object.nil? return 'null' elsif object.is_a?(String) return format_string_to_pdf object elsif object.is_a?(Symbol) return format_name_to_pdf object elsif object.is_a?(Array) return format_array_to_pdf object elsif object.is_a?(Integer) || object.is_a?(TrueClass) || object.is_a?(FalseClass) return object.to_s elsif object.is_a?(Numeric) # Float or other non-integer return sprintf('%f', object) elsif object.is_a?(Hash) return format_hash_to_pdf object else return '' end end
ruby
def object_to_pdf(object) if object.nil? return 'null' elsif object.is_a?(String) return format_string_to_pdf object elsif object.is_a?(Symbol) return format_name_to_pdf object elsif object.is_a?(Array) return format_array_to_pdf object elsif object.is_a?(Integer) || object.is_a?(TrueClass) || object.is_a?(FalseClass) return object.to_s elsif object.is_a?(Numeric) # Float or other non-integer return sprintf('%f', object) elsif object.is_a?(Hash) return format_hash_to_pdf object else return '' end end
[ "def", "object_to_pdf", "(", "object", ")", "if", "object", ".", "nil?", "return", "'null'", "elsif", "object", ".", "is_a?", "(", "String", ")", "return", "format_string_to_pdf", "object", "elsif", "object", ".", "is_a?", "(", "Symbol", ")", "return", "format_name_to_pdf", "object", "elsif", "object", ".", "is_a?", "(", "Array", ")", "return", "format_array_to_pdf", "object", "elsif", "object", ".", "is_a?", "(", "Integer", ")", "||", "object", ".", "is_a?", "(", "TrueClass", ")", "||", "object", ".", "is_a?", "(", "FalseClass", ")", "return", "object", ".", "to_s", "elsif", "object", ".", "is_a?", "(", "Numeric", ")", "# Float or other non-integer", "return", "sprintf", "(", "'%f'", ",", "object", ")", "elsif", "object", ".", "is_a?", "(", "Hash", ")", "return", "format_hash_to_pdf", "object", "else", "return", "''", "end", "end" ]
Formats an object into PDF format. This is used my the PDF object to format the PDF file and it is used in the secure injection which is still being developed.
[ "Formats", "an", "object", "into", "PDF", "format", ".", "This", "is", "used", "my", "the", "PDF", "object", "to", "format", "the", "PDF", "file", "and", "it", "is", "used", "in", "the", "secure", "injection", "which", "is", "still", "being", "developed", "." ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/renderer.rb#L14-L32
12,885
boazsegev/combine_pdf
lib/combine_pdf/pdf_public.rb
CombinePDF.PDF.new_page
def new_page(mediabox = [0, 0, 612.0, 792.0], _location = -1) p = PDFWriter.new(mediabox) insert(-1, p) p end
ruby
def new_page(mediabox = [0, 0, 612.0, 792.0], _location = -1) p = PDFWriter.new(mediabox) insert(-1, p) p end
[ "def", "new_page", "(", "mediabox", "=", "[", "0", ",", "0", ",", "612.0", ",", "792.0", "]", ",", "_location", "=", "-", "1", ")", "p", "=", "PDFWriter", ".", "new", "(", "mediabox", ")", "insert", "(", "-", "1", ",", "p", ")", "p", "end" ]
adds a new page to the end of the PDF object. returns the new page object. unless the media box is specified, it defaults to US Letter: [0, 0, 612.0, 792.0]
[ "adds", "a", "new", "page", "to", "the", "end", "of", "the", "PDF", "object", "." ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/pdf_public.rb#L122-L126
12,886
boazsegev/combine_pdf
lib/combine_pdf/pdf_public.rb
CombinePDF.PDF.to_pdf
def to_pdf(options = {}) # reset version if not specified @version = 1.5 if @version.to_f == 0.0 # set info for merged file @info[:ModDate] = @info[:CreationDate] = Time.now.strftime "D:%Y%m%d%H%M%S%:::z'00" @info[:Subject] = options[:subject] if options[:subject] @info[:Producer] = options[:producer] if options[:producer] # rebuild_catalog catalog = rebuild_catalog_and_objects # add ID and generation numbers to objects renumber_object_ids out = [] xref = [] indirect_object_count = 1 # the first object is the null object # write head (version and binanry-code) out << "%PDF-#{@version}\n%\xFF\xFF\xFF\xFF\xFF\x00\x00\x00\x00".force_encoding(Encoding::ASCII_8BIT) # collect objects and set xref table locations loc = 0 out.each { |line| loc += line.bytesize + 1 } @objects.each do |o| indirect_object_count += 1 xref << loc out << object_to_pdf(o) loc += out.last.bytesize + 1 end xref_location = loc # xref_location = 0 # out.each { |line| xref_location += line.bytesize + 1} out << "xref\n0 #{indirect_object_count}\n0000000000 65535 f \n" xref.each { |offset| out << (out.pop + ("%010d 00000 n \n" % offset)) } out << out.pop + 'trailer' out << "<<\n/Root #{false || "#{catalog[:indirect_reference_id]} #{catalog[:indirect_generation_number]} R"}" out << "/Size #{indirect_object_count}" out << "/Info #{@info[:indirect_reference_id]} #{@info[:indirect_generation_number]} R" out << ">>\nstartxref\n#{xref_location}\n%%EOF" # when finished, remove the numbering system and keep only pointers remove_old_ids # output the pdf stream out.join("\n".force_encoding(Encoding::ASCII_8BIT)).force_encoding(Encoding::ASCII_8BIT) end
ruby
def to_pdf(options = {}) # reset version if not specified @version = 1.5 if @version.to_f == 0.0 # set info for merged file @info[:ModDate] = @info[:CreationDate] = Time.now.strftime "D:%Y%m%d%H%M%S%:::z'00" @info[:Subject] = options[:subject] if options[:subject] @info[:Producer] = options[:producer] if options[:producer] # rebuild_catalog catalog = rebuild_catalog_and_objects # add ID and generation numbers to objects renumber_object_ids out = [] xref = [] indirect_object_count = 1 # the first object is the null object # write head (version and binanry-code) out << "%PDF-#{@version}\n%\xFF\xFF\xFF\xFF\xFF\x00\x00\x00\x00".force_encoding(Encoding::ASCII_8BIT) # collect objects and set xref table locations loc = 0 out.each { |line| loc += line.bytesize + 1 } @objects.each do |o| indirect_object_count += 1 xref << loc out << object_to_pdf(o) loc += out.last.bytesize + 1 end xref_location = loc # xref_location = 0 # out.each { |line| xref_location += line.bytesize + 1} out << "xref\n0 #{indirect_object_count}\n0000000000 65535 f \n" xref.each { |offset| out << (out.pop + ("%010d 00000 n \n" % offset)) } out << out.pop + 'trailer' out << "<<\n/Root #{false || "#{catalog[:indirect_reference_id]} #{catalog[:indirect_generation_number]} R"}" out << "/Size #{indirect_object_count}" out << "/Info #{@info[:indirect_reference_id]} #{@info[:indirect_generation_number]} R" out << ">>\nstartxref\n#{xref_location}\n%%EOF" # when finished, remove the numbering system and keep only pointers remove_old_ids # output the pdf stream out.join("\n".force_encoding(Encoding::ASCII_8BIT)).force_encoding(Encoding::ASCII_8BIT) end
[ "def", "to_pdf", "(", "options", "=", "{", "}", ")", "# reset version if not specified", "@version", "=", "1.5", "if", "@version", ".", "to_f", "==", "0.0", "# set info for merged file", "@info", "[", ":ModDate", "]", "=", "@info", "[", ":CreationDate", "]", "=", "Time", ".", "now", ".", "strftime", "\"D:%Y%m%d%H%M%S%:::z'00\"", "@info", "[", ":Subject", "]", "=", "options", "[", ":subject", "]", "if", "options", "[", ":subject", "]", "@info", "[", ":Producer", "]", "=", "options", "[", ":producer", "]", "if", "options", "[", ":producer", "]", "# rebuild_catalog", "catalog", "=", "rebuild_catalog_and_objects", "# add ID and generation numbers to objects", "renumber_object_ids", "out", "=", "[", "]", "xref", "=", "[", "]", "indirect_object_count", "=", "1", "# the first object is the null object", "# write head (version and binanry-code)", "out", "<<", "\"%PDF-#{@version}\\n%\\xFF\\xFF\\xFF\\xFF\\xFF\\x00\\x00\\x00\\x00\"", ".", "force_encoding", "(", "Encoding", "::", "ASCII_8BIT", ")", "# collect objects and set xref table locations", "loc", "=", "0", "out", ".", "each", "{", "|", "line", "|", "loc", "+=", "line", ".", "bytesize", "+", "1", "}", "@objects", ".", "each", "do", "|", "o", "|", "indirect_object_count", "+=", "1", "xref", "<<", "loc", "out", "<<", "object_to_pdf", "(", "o", ")", "loc", "+=", "out", ".", "last", ".", "bytesize", "+", "1", "end", "xref_location", "=", "loc", "# xref_location = 0", "# out.each { |line| xref_location += line.bytesize + 1}", "out", "<<", "\"xref\\n0 #{indirect_object_count}\\n0000000000 65535 f \\n\"", "xref", ".", "each", "{", "|", "offset", "|", "out", "<<", "(", "out", ".", "pop", "+", "(", "\"%010d 00000 n \\n\"", "%", "offset", ")", ")", "}", "out", "<<", "out", ".", "pop", "+", "'trailer'", "out", "<<", "\"<<\\n/Root #{false || \"#{catalog[:indirect_reference_id]} #{catalog[:indirect_generation_number]} R\"}\"", "out", "<<", "\"/Size #{indirect_object_count}\"", "out", "<<", "\"/Info #{@info[:indirect_reference_id]} #{@info[:indirect_generation_number]} R\"", "out", "<<", "\">>\\nstartxref\\n#{xref_location}\\n%%EOF\"", "# when finished, remove the numbering system and keep only pointers", "remove_old_ids", "# output the pdf stream", "out", ".", "join", "(", "\"\\n\"", ".", "force_encoding", "(", "Encoding", "::", "ASCII_8BIT", ")", ")", ".", "force_encoding", "(", "Encoding", "::", "ASCII_8BIT", ")", "end" ]
Formats the data to PDF formats and returns a binary string that represents the PDF file content. This method is used by the save(file_name) method to save the content to a file. use this to export the PDF file without saving to disk (such as sending through HTTP ect').
[ "Formats", "the", "data", "to", "PDF", "formats", "and", "returns", "a", "binary", "string", "that", "represents", "the", "PDF", "file", "content", "." ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/pdf_public.rb#L174-L215
12,887
boazsegev/combine_pdf
lib/combine_pdf/pdf_public.rb
CombinePDF.PDF.pages
def pages(catalogs = nil) page_list = [] catalogs ||= get_existing_catalogs if catalogs.is_a?(Array) catalogs.each { |c| page_list.concat pages(c) unless c.nil? } elsif catalogs.is_a?(Hash) if catalogs[:is_reference_only] if catalogs[:referenced_object] page_list.concat pages(catalogs[:referenced_object]) else warn "couldn't follow reference!!! #{catalogs} not found!" end else case catalogs[:Type] when :Page page_list << catalogs when :Pages page_list.concat pages(catalogs[:Kids]) unless catalogs[:Kids].nil? when :Catalog page_list.concat pages(catalogs[:Pages]) unless catalogs[:Pages].nil? end end end page_list end
ruby
def pages(catalogs = nil) page_list = [] catalogs ||= get_existing_catalogs if catalogs.is_a?(Array) catalogs.each { |c| page_list.concat pages(c) unless c.nil? } elsif catalogs.is_a?(Hash) if catalogs[:is_reference_only] if catalogs[:referenced_object] page_list.concat pages(catalogs[:referenced_object]) else warn "couldn't follow reference!!! #{catalogs} not found!" end else case catalogs[:Type] when :Page page_list << catalogs when :Pages page_list.concat pages(catalogs[:Kids]) unless catalogs[:Kids].nil? when :Catalog page_list.concat pages(catalogs[:Pages]) unless catalogs[:Pages].nil? end end end page_list end
[ "def", "pages", "(", "catalogs", "=", "nil", ")", "page_list", "=", "[", "]", "catalogs", "||=", "get_existing_catalogs", "if", "catalogs", ".", "is_a?", "(", "Array", ")", "catalogs", ".", "each", "{", "|", "c", "|", "page_list", ".", "concat", "pages", "(", "c", ")", "unless", "c", ".", "nil?", "}", "elsif", "catalogs", ".", "is_a?", "(", "Hash", ")", "if", "catalogs", "[", ":is_reference_only", "]", "if", "catalogs", "[", ":referenced_object", "]", "page_list", ".", "concat", "pages", "(", "catalogs", "[", ":referenced_object", "]", ")", "else", "warn", "\"couldn't follow reference!!! #{catalogs} not found!\"", "end", "else", "case", "catalogs", "[", ":Type", "]", "when", ":Page", "page_list", "<<", "catalogs", "when", ":Pages", "page_list", ".", "concat", "pages", "(", "catalogs", "[", ":Kids", "]", ")", "unless", "catalogs", "[", ":Kids", "]", ".", "nil?", "when", ":Catalog", "page_list", ".", "concat", "pages", "(", "catalogs", "[", ":Pages", "]", ")", "unless", "catalogs", "[", ":Pages", "]", ".", "nil?", "end", "end", "end", "page_list", "end" ]
this method returns all the pages cataloged in the catalog. if no catalog is passed, it seeks the existing catalog(s) and searches for any registered Page objects. Page objects are Hash class objects. the page methods are added using a mixin or inheritance. catalogs:: a catalog, or an Array of catalog objects. defaults to the existing catalog.
[ "this", "method", "returns", "all", "the", "pages", "cataloged", "in", "the", "catalog", "." ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/pdf_public.rb#L225-L250
12,888
boazsegev/combine_pdf
lib/combine_pdf/pdf_public.rb
CombinePDF.PDF.fonts
def fonts(limit_to_type0 = false) fonts_array = [] pages.each do |pg| if pg[:Resources][:Font] pg[:Resources][:Font].values.each do |f| f = f[:referenced_object] if f[:referenced_object] if (limit_to_type0 || f[:Subtype] == :Type0) && f[:Type] == :Font && !fonts_array.include?(f) fonts_array << f end end end end fonts_array end
ruby
def fonts(limit_to_type0 = false) fonts_array = [] pages.each do |pg| if pg[:Resources][:Font] pg[:Resources][:Font].values.each do |f| f = f[:referenced_object] if f[:referenced_object] if (limit_to_type0 || f[:Subtype] == :Type0) && f[:Type] == :Font && !fonts_array.include?(f) fonts_array << f end end end end fonts_array end
[ "def", "fonts", "(", "limit_to_type0", "=", "false", ")", "fonts_array", "=", "[", "]", "pages", ".", "each", "do", "|", "pg", "|", "if", "pg", "[", ":Resources", "]", "[", ":Font", "]", "pg", "[", ":Resources", "]", "[", ":Font", "]", ".", "values", ".", "each", "do", "|", "f", "|", "f", "=", "f", "[", ":referenced_object", "]", "if", "f", "[", ":referenced_object", "]", "if", "(", "limit_to_type0", "||", "f", "[", ":Subtype", "]", "==", ":Type0", ")", "&&", "f", "[", ":Type", "]", "==", ":Font", "&&", "!", "fonts_array", ".", "include?", "(", "f", ")", "fonts_array", "<<", "f", "end", "end", "end", "end", "fonts_array", "end" ]
returns an array with the different fonts used in the file. Type0 font objects ( "font[:Subtype] == :Type0" ) can be registered with the font library for use in PDFWriter objects (font numbering / table creation etc'). @param limit_to_type0 [true,false] limits the list to type0 fonts.
[ "returns", "an", "array", "with", "the", "different", "fonts", "used", "in", "the", "file", "." ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/pdf_public.rb#L257-L270
12,889
boazsegev/combine_pdf
lib/combine_pdf/pdf_public.rb
CombinePDF.PDF.remove
def remove(page_index) catalog = rebuild_catalog pages_array = catalog[:Pages][:referenced_object][:Kids] removed_page = pages_array.delete_at page_index catalog[:Pages][:referenced_object][:Count] = pages_array.length removed_page end
ruby
def remove(page_index) catalog = rebuild_catalog pages_array = catalog[:Pages][:referenced_object][:Kids] removed_page = pages_array.delete_at page_index catalog[:Pages][:referenced_object][:Count] = pages_array.length removed_page end
[ "def", "remove", "(", "page_index", ")", "catalog", "=", "rebuild_catalog", "pages_array", "=", "catalog", "[", ":Pages", "]", "[", ":referenced_object", "]", "[", ":Kids", "]", "removed_page", "=", "pages_array", ".", "delete_at", "page_index", "catalog", "[", ":Pages", "]", "[", ":referenced_object", "]", "[", ":Count", "]", "=", "pages_array", ".", "length", "removed_page", "end" ]
removes a PDF page from the file and the catalog returns the removed page. returns nil if failed or if out of bounds. page_index:: the page's index in the zero (0) based page array. negative numbers represent a count backwards (-1 being the end of the page array and 0 being the begining).
[ "removes", "a", "PDF", "page", "from", "the", "file", "and", "the", "catalog" ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/pdf_public.rb#L346-L352
12,890
boazsegev/combine_pdf
lib/combine_pdf/fonts.rb
CombinePDF.Fonts.register_font_from_pdf_object
def register_font_from_pdf_object(font_name, font_object) # FIXME: # - add stream deflation for the CMap file. # - add :Encoding CMaps (such as :WinAnsiEncoding etc`) # - the ToUnicode CMap parsing assumes 8 Bytes <0F0F> while 16 Bytes and multiple unicode chars are also possible. # first, create cmap, as it will be used to correctly create the widths directory. # find the CMap from one of the two systems (TrueType vs. Type0 fonts) # at the moment doen't suppot :Encoding cmaps... cmap = {} if font_object[:ToUnicode] to_unicode = font_object[:ToUnicode] to_unicode = to_unicode[:referenced_object] if to_unicode[:is_reference_only] # deflate the cmap file stream before parsing to_unicode = create_deep_copy to_unicode CombinePDF::PDFFilter.inflate_object to_unicode # parse the deflated stream cmap = parse_cmap to_unicode[:raw_stream_content] else warn "didn't find ToUnicode object for #{font_object}" return false end # second, create the metrics directory. metrics = {} old_widths = font_object if font_object[:DescendantFonts] old_widths = font_object[:DescendantFonts] old_widths = old_widths[:referenced_object][:indirect_without_dictionary] if old_widths.is_a?(Hash) && old_widths[:is_reference_only] old_widths = old_widths[0][:referenced_object] avrg_height = 360 avrg_height = old_widths[:XHeight] if old_widths[:XHeight] avrg_height = (avrg_height + old_widths[:CapHeight]) / 2 if old_widths[:CapHeight] avrg_width = old_widths[:AvgWidth] || 0 avarage_bbox = [0, 0, avrg_width, avrg_height] # data is missing for full box metrics, just ignore end # compute the metrics values using the appropiate system (TrueType vs. Type0 fonts) cmap_inverted = {} cmap.each { |k, v| cmap_inverted[v.hex] = k } if old_widths[:W] old_widths = old_widths[:W] if old_widths.is_a?(Hash) && old_widths[:is_reference_only] old_widths = old_widths[:referenced_object][:indirect_without_dictionary] end old_widths = create_deep_copy old_widths while old_widths[0] a = old_widths.shift b = old_widths.shift if b.is_a?(Array) b.each_index { |i| metrics[cmap_inverted[(a + i)] || (a + i)] = { wx: b[i], boundingbox: avarage_bbox } } else c = old_widths.shift (b - a).times { |i| metrics[cmap_inverted[(a + i)] || (a + i)] = { wx: c[0], boundingbox: avarage_bbox } } end end elsif old_widths[:Widths] first_char = old_widths[:FirstChar] old_widths = old_widths[:Widths] if old_widths.is_a?(Hash) && old_widths[:is_reference_only] old_widths = old_widths[:referenced_object][:indirect_without_dictionary] end old_widths.each_index { |i| metrics[cmap_inverted[(i + first_char)] || (i + first_char)] = { wx: old_widths[i], boundingbox: avarage_bbox } } else warn "didn't find widths object for #{old_widths}" return false end # register the font and return the font object cmap = nil if cmap.empty? CombinePDF::Fonts.register_font font_name, metrics, font_object, cmap end
ruby
def register_font_from_pdf_object(font_name, font_object) # FIXME: # - add stream deflation for the CMap file. # - add :Encoding CMaps (such as :WinAnsiEncoding etc`) # - the ToUnicode CMap parsing assumes 8 Bytes <0F0F> while 16 Bytes and multiple unicode chars are also possible. # first, create cmap, as it will be used to correctly create the widths directory. # find the CMap from one of the two systems (TrueType vs. Type0 fonts) # at the moment doen't suppot :Encoding cmaps... cmap = {} if font_object[:ToUnicode] to_unicode = font_object[:ToUnicode] to_unicode = to_unicode[:referenced_object] if to_unicode[:is_reference_only] # deflate the cmap file stream before parsing to_unicode = create_deep_copy to_unicode CombinePDF::PDFFilter.inflate_object to_unicode # parse the deflated stream cmap = parse_cmap to_unicode[:raw_stream_content] else warn "didn't find ToUnicode object for #{font_object}" return false end # second, create the metrics directory. metrics = {} old_widths = font_object if font_object[:DescendantFonts] old_widths = font_object[:DescendantFonts] old_widths = old_widths[:referenced_object][:indirect_without_dictionary] if old_widths.is_a?(Hash) && old_widths[:is_reference_only] old_widths = old_widths[0][:referenced_object] avrg_height = 360 avrg_height = old_widths[:XHeight] if old_widths[:XHeight] avrg_height = (avrg_height + old_widths[:CapHeight]) / 2 if old_widths[:CapHeight] avrg_width = old_widths[:AvgWidth] || 0 avarage_bbox = [0, 0, avrg_width, avrg_height] # data is missing for full box metrics, just ignore end # compute the metrics values using the appropiate system (TrueType vs. Type0 fonts) cmap_inverted = {} cmap.each { |k, v| cmap_inverted[v.hex] = k } if old_widths[:W] old_widths = old_widths[:W] if old_widths.is_a?(Hash) && old_widths[:is_reference_only] old_widths = old_widths[:referenced_object][:indirect_without_dictionary] end old_widths = create_deep_copy old_widths while old_widths[0] a = old_widths.shift b = old_widths.shift if b.is_a?(Array) b.each_index { |i| metrics[cmap_inverted[(a + i)] || (a + i)] = { wx: b[i], boundingbox: avarage_bbox } } else c = old_widths.shift (b - a).times { |i| metrics[cmap_inverted[(a + i)] || (a + i)] = { wx: c[0], boundingbox: avarage_bbox } } end end elsif old_widths[:Widths] first_char = old_widths[:FirstChar] old_widths = old_widths[:Widths] if old_widths.is_a?(Hash) && old_widths[:is_reference_only] old_widths = old_widths[:referenced_object][:indirect_without_dictionary] end old_widths.each_index { |i| metrics[cmap_inverted[(i + first_char)] || (i + first_char)] = { wx: old_widths[i], boundingbox: avarage_bbox } } else warn "didn't find widths object for #{old_widths}" return false end # register the font and return the font object cmap = nil if cmap.empty? CombinePDF::Fonts.register_font font_name, metrics, font_object, cmap end
[ "def", "register_font_from_pdf_object", "(", "font_name", ",", "font_object", ")", "# FIXME:", "# - add stream deflation for the CMap file.", "# - add :Encoding CMaps (such as :WinAnsiEncoding etc`)", "# - the ToUnicode CMap parsing assumes 8 Bytes <0F0F> while 16 Bytes and multiple unicode chars are also possible.", "# first, create cmap, as it will be used to correctly create the widths directory.", "# find the CMap from one of the two systems (TrueType vs. Type0 fonts)", "# at the moment doen't suppot :Encoding cmaps...", "cmap", "=", "{", "}", "if", "font_object", "[", ":ToUnicode", "]", "to_unicode", "=", "font_object", "[", ":ToUnicode", "]", "to_unicode", "=", "to_unicode", "[", ":referenced_object", "]", "if", "to_unicode", "[", ":is_reference_only", "]", "# deflate the cmap file stream before parsing", "to_unicode", "=", "create_deep_copy", "to_unicode", "CombinePDF", "::", "PDFFilter", ".", "inflate_object", "to_unicode", "# parse the deflated stream", "cmap", "=", "parse_cmap", "to_unicode", "[", ":raw_stream_content", "]", "else", "warn", "\"didn't find ToUnicode object for #{font_object}\"", "return", "false", "end", "# second, create the metrics directory.", "metrics", "=", "{", "}", "old_widths", "=", "font_object", "if", "font_object", "[", ":DescendantFonts", "]", "old_widths", "=", "font_object", "[", ":DescendantFonts", "]", "old_widths", "=", "old_widths", "[", ":referenced_object", "]", "[", ":indirect_without_dictionary", "]", "if", "old_widths", ".", "is_a?", "(", "Hash", ")", "&&", "old_widths", "[", ":is_reference_only", "]", "old_widths", "=", "old_widths", "[", "0", "]", "[", ":referenced_object", "]", "avrg_height", "=", "360", "avrg_height", "=", "old_widths", "[", ":XHeight", "]", "if", "old_widths", "[", ":XHeight", "]", "avrg_height", "=", "(", "avrg_height", "+", "old_widths", "[", ":CapHeight", "]", ")", "/", "2", "if", "old_widths", "[", ":CapHeight", "]", "avrg_width", "=", "old_widths", "[", ":AvgWidth", "]", "||", "0", "avarage_bbox", "=", "[", "0", ",", "0", ",", "avrg_width", ",", "avrg_height", "]", "# data is missing for full box metrics, just ignore", "end", "# compute the metrics values using the appropiate system (TrueType vs. Type0 fonts)", "cmap_inverted", "=", "{", "}", "cmap", ".", "each", "{", "|", "k", ",", "v", "|", "cmap_inverted", "[", "v", ".", "hex", "]", "=", "k", "}", "if", "old_widths", "[", ":W", "]", "old_widths", "=", "old_widths", "[", ":W", "]", "if", "old_widths", ".", "is_a?", "(", "Hash", ")", "&&", "old_widths", "[", ":is_reference_only", "]", "old_widths", "=", "old_widths", "[", ":referenced_object", "]", "[", ":indirect_without_dictionary", "]", "end", "old_widths", "=", "create_deep_copy", "old_widths", "while", "old_widths", "[", "0", "]", "a", "=", "old_widths", ".", "shift", "b", "=", "old_widths", ".", "shift", "if", "b", ".", "is_a?", "(", "Array", ")", "b", ".", "each_index", "{", "|", "i", "|", "metrics", "[", "cmap_inverted", "[", "(", "a", "+", "i", ")", "]", "||", "(", "a", "+", "i", ")", "]", "=", "{", "wx", ":", "b", "[", "i", "]", ",", "boundingbox", ":", "avarage_bbox", "}", "}", "else", "c", "=", "old_widths", ".", "shift", "(", "b", "-", "a", ")", ".", "times", "{", "|", "i", "|", "metrics", "[", "cmap_inverted", "[", "(", "a", "+", "i", ")", "]", "||", "(", "a", "+", "i", ")", "]", "=", "{", "wx", ":", "c", "[", "0", "]", ",", "boundingbox", ":", "avarage_bbox", "}", "}", "end", "end", "elsif", "old_widths", "[", ":Widths", "]", "first_char", "=", "old_widths", "[", ":FirstChar", "]", "old_widths", "=", "old_widths", "[", ":Widths", "]", "if", "old_widths", ".", "is_a?", "(", "Hash", ")", "&&", "old_widths", "[", ":is_reference_only", "]", "old_widths", "=", "old_widths", "[", ":referenced_object", "]", "[", ":indirect_without_dictionary", "]", "end", "old_widths", ".", "each_index", "{", "|", "i", "|", "metrics", "[", "cmap_inverted", "[", "(", "i", "+", "first_char", ")", "]", "||", "(", "i", "+", "first_char", ")", "]", "=", "{", "wx", ":", "old_widths", "[", "i", "]", ",", "boundingbox", ":", "avarage_bbox", "}", "}", "else", "warn", "\"didn't find widths object for #{old_widths}\"", "return", "false", "end", "# register the font and return the font object", "cmap", "=", "nil", "if", "cmap", ".", "empty?", "CombinePDF", "::", "Fonts", ".", "register_font", "font_name", ",", "metrics", ",", "font_object", ",", "cmap", "end" ]
Register a font that already exists in a pdf object into the font library. The implementation is experimental, but this function attempts to deconstruct a font object in order to extract it's cmap and metric data, allowing it's use in the CombinePDF library.
[ "Register", "a", "font", "that", "already", "exists", "in", "a", "pdf", "object", "into", "the", "font", "library", "." ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/fonts.rb#L205-L277
12,891
boazsegev/combine_pdf
lib/combine_pdf/page_methods.rb
CombinePDF.Page_Methods.init_contents
def init_contents self[:Contents] = self[:Contents][:referenced_object][:indirect_without_dictionary] if self[:Contents].is_a?(Hash) && self[:Contents][:referenced_object] && self[:Contents][:referenced_object].is_a?(Hash) && self[:Contents][:referenced_object][:indirect_without_dictionary] self[:Contents] = [self[:Contents]] unless self[:Contents].is_a?(Array) self[:Contents].delete(is_reference_only: true, referenced_object: { indirect_reference_id: 0, raw_stream_content: '' }) # un-nest any referenced arrays self[:Contents].map! { |s| actual_value(s).is_a?(Array) ? actual_value(s) : s } self[:Contents].flatten! self[:Contents].compact! # wrap content streams insert_content 'q', 0 insert_content 'Q' # Prep content @contents = '' insert_content @contents @contents end
ruby
def init_contents self[:Contents] = self[:Contents][:referenced_object][:indirect_without_dictionary] if self[:Contents].is_a?(Hash) && self[:Contents][:referenced_object] && self[:Contents][:referenced_object].is_a?(Hash) && self[:Contents][:referenced_object][:indirect_without_dictionary] self[:Contents] = [self[:Contents]] unless self[:Contents].is_a?(Array) self[:Contents].delete(is_reference_only: true, referenced_object: { indirect_reference_id: 0, raw_stream_content: '' }) # un-nest any referenced arrays self[:Contents].map! { |s| actual_value(s).is_a?(Array) ? actual_value(s) : s } self[:Contents].flatten! self[:Contents].compact! # wrap content streams insert_content 'q', 0 insert_content 'Q' # Prep content @contents = '' insert_content @contents @contents end
[ "def", "init_contents", "self", "[", ":Contents", "]", "=", "self", "[", ":Contents", "]", "[", ":referenced_object", "]", "[", ":indirect_without_dictionary", "]", "if", "self", "[", ":Contents", "]", ".", "is_a?", "(", "Hash", ")", "&&", "self", "[", ":Contents", "]", "[", ":referenced_object", "]", "&&", "self", "[", ":Contents", "]", "[", ":referenced_object", "]", ".", "is_a?", "(", "Hash", ")", "&&", "self", "[", ":Contents", "]", "[", ":referenced_object", "]", "[", ":indirect_without_dictionary", "]", "self", "[", ":Contents", "]", "=", "[", "self", "[", ":Contents", "]", "]", "unless", "self", "[", ":Contents", "]", ".", "is_a?", "(", "Array", ")", "self", "[", ":Contents", "]", ".", "delete", "(", "is_reference_only", ":", "true", ",", "referenced_object", ":", "{", "indirect_reference_id", ":", "0", ",", "raw_stream_content", ":", "''", "}", ")", "# un-nest any referenced arrays", "self", "[", ":Contents", "]", ".", "map!", "{", "|", "s", "|", "actual_value", "(", "s", ")", ".", "is_a?", "(", "Array", ")", "?", "actual_value", "(", "s", ")", ":", "s", "}", "self", "[", ":Contents", "]", ".", "flatten!", "self", "[", ":Contents", "]", ".", "compact!", "# wrap content streams", "insert_content", "'q'", ",", "0", "insert_content", "'Q'", "# Prep content", "@contents", "=", "''", "insert_content", "@contents", "@contents", "end" ]
initializes the content stream in case it was not initialized before
[ "initializes", "the", "content", "stream", "in", "case", "it", "was", "not", "initialized", "before" ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/page_methods.rb#L669-L685
12,892
boazsegev/combine_pdf
lib/combine_pdf/page_methods.rb
CombinePDF.Page_Methods.insert_content
def insert_content(object, location = -1) object = { is_reference_only: true, referenced_object: { indirect_reference_id: 0, raw_stream_content: object } } if object.is_a?(String) raise TypeError, 'expected a String or Hash object.' unless object.is_a?(Hash) prep_content_array self[:Contents].insert location, object self[:Contents].flatten! self end
ruby
def insert_content(object, location = -1) object = { is_reference_only: true, referenced_object: { indirect_reference_id: 0, raw_stream_content: object } } if object.is_a?(String) raise TypeError, 'expected a String or Hash object.' unless object.is_a?(Hash) prep_content_array self[:Contents].insert location, object self[:Contents].flatten! self end
[ "def", "insert_content", "(", "object", ",", "location", "=", "-", "1", ")", "object", "=", "{", "is_reference_only", ":", "true", ",", "referenced_object", ":", "{", "indirect_reference_id", ":", "0", ",", "raw_stream_content", ":", "object", "}", "}", "if", "object", ".", "is_a?", "(", "String", ")", "raise", "TypeError", ",", "'expected a String or Hash object.'", "unless", "object", ".", "is_a?", "(", "Hash", ")", "prep_content_array", "self", "[", ":Contents", "]", ".", "insert", "location", ",", "object", "self", "[", ":Contents", "]", ".", "flatten!", "self", "end" ]
adds a string or an object to the content stream, at the location indicated accepts: object:: can be a string or a hash object location:: can be any numeral related to the possition in the :Contents array. defaults to -1 == insert at the end.
[ "adds", "a", "string", "or", "an", "object", "to", "the", "content", "stream", "at", "the", "location", "indicated" ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/page_methods.rb#L692-L699
12,893
boazsegev/combine_pdf
lib/combine_pdf/page_methods.rb
CombinePDF.Page_Methods.graphic_state
def graphic_state(graphic_state_dictionary = {}) # if the graphic state exists, return it's name resources[:ExtGState] ||= {} gs_res = resources[:ExtGState][:referenced_object] || resources[:ExtGState] gs_res.each do |k, v| return k if v.is_a?(Hash) && v == graphic_state_dictionary end # set graphic state type graphic_state_dictionary[:Type] = :ExtGState # set a secure name for the graphic state name = SecureRandom.hex(9).to_sym # add object to reasource gs_res[name] = graphic_state_dictionary # return name name end
ruby
def graphic_state(graphic_state_dictionary = {}) # if the graphic state exists, return it's name resources[:ExtGState] ||= {} gs_res = resources[:ExtGState][:referenced_object] || resources[:ExtGState] gs_res.each do |k, v| return k if v.is_a?(Hash) && v == graphic_state_dictionary end # set graphic state type graphic_state_dictionary[:Type] = :ExtGState # set a secure name for the graphic state name = SecureRandom.hex(9).to_sym # add object to reasource gs_res[name] = graphic_state_dictionary # return name name end
[ "def", "graphic_state", "(", "graphic_state_dictionary", "=", "{", "}", ")", "# if the graphic state exists, return it's name", "resources", "[", ":ExtGState", "]", "||=", "{", "}", "gs_res", "=", "resources", "[", ":ExtGState", "]", "[", ":referenced_object", "]", "||", "resources", "[", ":ExtGState", "]", "gs_res", ".", "each", "do", "|", "k", ",", "v", "|", "return", "k", "if", "v", ".", "is_a?", "(", "Hash", ")", "&&", "v", "==", "graphic_state_dictionary", "end", "# set graphic state type", "graphic_state_dictionary", "[", ":Type", "]", "=", ":ExtGState", "# set a secure name for the graphic state", "name", "=", "SecureRandom", ".", "hex", "(", "9", ")", ".", "to_sym", "# add object to reasource", "gs_res", "[", "name", "]", "=", "graphic_state_dictionary", "# return name", "name", "end" ]
register or get a registered graphic state dictionary. the method returns the name of the graphos state, for use in a content stream.
[ "register", "or", "get", "a", "registered", "graphic", "state", "dictionary", ".", "the", "method", "returns", "the", "name", "of", "the", "graphos", "state", "for", "use", "in", "a", "content", "stream", "." ]
09054051019c069f551f3e60be789577c0f93900
https://github.com/boazsegev/combine_pdf/blob/09054051019c069f551f3e60be789577c0f93900/lib/combine_pdf/page_methods.rb#L754-L769
12,894
shugo/textbringer
lib/textbringer/buffer.rb
Textbringer.Buffer.save_excursion
def save_excursion old_point = new_mark old_mark = @mark&.dup old_column = @goal_column begin yield ensure point_to_mark(old_point) old_point.delete if old_mark @mark.location = old_mark.location old_mark.delete end @goal_column = old_column end end
ruby
def save_excursion old_point = new_mark old_mark = @mark&.dup old_column = @goal_column begin yield ensure point_to_mark(old_point) old_point.delete if old_mark @mark.location = old_mark.location old_mark.delete end @goal_column = old_column end end
[ "def", "save_excursion", "old_point", "=", "new_mark", "old_mark", "=", "@mark", "&.", "dup", "old_column", "=", "@goal_column", "begin", "yield", "ensure", "point_to_mark", "(", "old_point", ")", "old_point", ".", "delete", "if", "old_mark", "@mark", ".", "location", "=", "old_mark", ".", "location", "old_mark", ".", "delete", "end", "@goal_column", "=", "old_column", "end", "end" ]
Don't save Buffer.current.
[ "Don", "t", "save", "Buffer", ".", "current", "." ]
dcea7a098b5e04335e73faee5616bd1678add7ec
https://github.com/shugo/textbringer/blob/dcea7a098b5e04335e73faee5616bd1678add7ec/lib/textbringer/buffer.rb#L813-L828
12,895
shugo/textbringer
lib/textbringer/buffer.rb
Textbringer.Buffer.push_mark
def push_mark(pos = @point) @mark = new_mark @mark.location = pos @mark_ring.push(@mark) if self != Buffer.minibuffer global_mark_ring = Buffer.global_mark_ring if global_mark_ring.empty? || global_mark_ring.current.buffer != self push_global_mark(pos) end end end
ruby
def push_mark(pos = @point) @mark = new_mark @mark.location = pos @mark_ring.push(@mark) if self != Buffer.minibuffer global_mark_ring = Buffer.global_mark_ring if global_mark_ring.empty? || global_mark_ring.current.buffer != self push_global_mark(pos) end end end
[ "def", "push_mark", "(", "pos", "=", "@point", ")", "@mark", "=", "new_mark", "@mark", ".", "location", "=", "pos", "@mark_ring", ".", "push", "(", "@mark", ")", "if", "self", "!=", "Buffer", ".", "minibuffer", "global_mark_ring", "=", "Buffer", ".", "global_mark_ring", "if", "global_mark_ring", ".", "empty?", "||", "global_mark_ring", ".", "current", ".", "buffer", "!=", "self", "push_global_mark", "(", "pos", ")", "end", "end", "end" ]
Set mark at pos, and push the mark on the mark ring. Unlike Emacs, the new mark is pushed on the mark ring instead of the old one.
[ "Set", "mark", "at", "pos", "and", "push", "the", "mark", "on", "the", "mark", "ring", ".", "Unlike", "Emacs", "the", "new", "mark", "is", "pushed", "on", "the", "mark", "ring", "instead", "of", "the", "old", "one", "." ]
dcea7a098b5e04335e73faee5616bd1678add7ec
https://github.com/shugo/textbringer/blob/dcea7a098b5e04335e73faee5616bd1678add7ec/lib/textbringer/buffer.rb#L848-L858
12,896
shugo/textbringer
lib/textbringer/modes/programming_mode.rb
Textbringer.ProgrammingMode.indent_line
def indent_line result = false level = calculate_indentation return result if level.nil? @buffer.save_excursion do @buffer.beginning_of_line @buffer.composite_edit do if @buffer.looking_at?(/[ \t]+/) s = @buffer.match_string(0) break if /\t/ !~ s && s.size == level @buffer.delete_region(@buffer.match_beginning(0), @buffer.match_end(0)) else break if level == 0 end @buffer.indent_to(level) end result = true end pos = @buffer.point @buffer.beginning_of_line @buffer.forward_char while /[ \t]/ =~ @buffer.char_after if @buffer.point < pos @buffer.goto_char(pos) end result end
ruby
def indent_line result = false level = calculate_indentation return result if level.nil? @buffer.save_excursion do @buffer.beginning_of_line @buffer.composite_edit do if @buffer.looking_at?(/[ \t]+/) s = @buffer.match_string(0) break if /\t/ !~ s && s.size == level @buffer.delete_region(@buffer.match_beginning(0), @buffer.match_end(0)) else break if level == 0 end @buffer.indent_to(level) end result = true end pos = @buffer.point @buffer.beginning_of_line @buffer.forward_char while /[ \t]/ =~ @buffer.char_after if @buffer.point < pos @buffer.goto_char(pos) end result end
[ "def", "indent_line", "result", "=", "false", "level", "=", "calculate_indentation", "return", "result", "if", "level", ".", "nil?", "@buffer", ".", "save_excursion", "do", "@buffer", ".", "beginning_of_line", "@buffer", ".", "composite_edit", "do", "if", "@buffer", ".", "looking_at?", "(", "/", "\\t", "/", ")", "s", "=", "@buffer", ".", "match_string", "(", "0", ")", "break", "if", "/", "\\t", "/", "!~", "s", "&&", "s", ".", "size", "==", "level", "@buffer", ".", "delete_region", "(", "@buffer", ".", "match_beginning", "(", "0", ")", ",", "@buffer", ".", "match_end", "(", "0", ")", ")", "else", "break", "if", "level", "==", "0", "end", "@buffer", ".", "indent_to", "(", "level", ")", "end", "result", "=", "true", "end", "pos", "=", "@buffer", ".", "point", "@buffer", ".", "beginning_of_line", "@buffer", ".", "forward_char", "while", "/", "\\t", "/", "=~", "@buffer", ".", "char_after", "if", "@buffer", ".", "point", "<", "pos", "@buffer", ".", "goto_char", "(", "pos", ")", "end", "result", "end" ]
Return true if modified.
[ "Return", "true", "if", "modified", "." ]
dcea7a098b5e04335e73faee5616bd1678add7ec
https://github.com/shugo/textbringer/blob/dcea7a098b5e04335e73faee5616bd1678add7ec/lib/textbringer/modes/programming_mode.rb#L32-L58
12,897
Eric-Guo/wechat
lib/wechat/cipher.rb
Wechat.Cipher.pack
def pack(content, app_id) random = SecureRandom.hex(8) text = content.force_encoding('ASCII-8BIT') msg_len = [text.length].pack('N') encode_padding("#{random}#{msg_len}#{text}#{app_id}") end
ruby
def pack(content, app_id) random = SecureRandom.hex(8) text = content.force_encoding('ASCII-8BIT') msg_len = [text.length].pack('N') encode_padding("#{random}#{msg_len}#{text}#{app_id}") end
[ "def", "pack", "(", "content", ",", "app_id", ")", "random", "=", "SecureRandom", ".", "hex", "(", "8", ")", "text", "=", "content", ".", "force_encoding", "(", "'ASCII-8BIT'", ")", "msg_len", "=", "[", "text", ".", "length", "]", ".", "pack", "(", "'N'", ")", "encode_padding", "(", "\"#{random}#{msg_len}#{text}#{app_id}\"", ")", "end" ]
app_id or corp_id
[ "app_id", "or", "corp_id" ]
2adcd4b3ad30cfe74930dec3ed8c7f4fdb1e6ec9
https://github.com/Eric-Guo/wechat/blob/2adcd4b3ad30cfe74930dec3ed8c7f4fdb1e6ec9/lib/wechat/cipher.rb#L32-L38
12,898
seejohnrun/ice_cube
lib/ice_cube/validations/fixed_value.rb
IceCube.Validations::FixedValue.validate_interval_lock
def validate_interval_lock(time, start_time) t0 = starting_unit(start_time) t1 = time.send(type) t0 >= t1 ? t0 - t1 : INTERVALS[type] - t1 + t0 end
ruby
def validate_interval_lock(time, start_time) t0 = starting_unit(start_time) t1 = time.send(type) t0 >= t1 ? t0 - t1 : INTERVALS[type] - t1 + t0 end
[ "def", "validate_interval_lock", "(", "time", ",", "start_time", ")", "t0", "=", "starting_unit", "(", "start_time", ")", "t1", "=", "time", ".", "send", "(", "type", ")", "t0", ">=", "t1", "?", "t0", "-", "t1", ":", "INTERVALS", "[", "type", "]", "-", "t1", "+", "t0", "end" ]
Validate if the current time unit matches the same unit from the schedule start time, returning the difference to the interval
[ "Validate", "if", "the", "current", "time", "unit", "matches", "the", "same", "unit", "from", "the", "schedule", "start", "time", "returning", "the", "difference", "to", "the", "interval" ]
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/validations/fixed_value.rb#L28-L32
12,899
seejohnrun/ice_cube
lib/ice_cube/validations/fixed_value.rb
IceCube.Validations::FixedValue.validate_hour_lock
def validate_hour_lock(time, start_time) h0 = starting_unit(start_time) h1 = time.hour if h0 >= h1 h0 - h1 else if dst_offset = TimeUtil.dst_change(time) h0 - h1 + dst_offset else 24 - h1 + h0 end end end
ruby
def validate_hour_lock(time, start_time) h0 = starting_unit(start_time) h1 = time.hour if h0 >= h1 h0 - h1 else if dst_offset = TimeUtil.dst_change(time) h0 - h1 + dst_offset else 24 - h1 + h0 end end end
[ "def", "validate_hour_lock", "(", "time", ",", "start_time", ")", "h0", "=", "starting_unit", "(", "start_time", ")", "h1", "=", "time", ".", "hour", "if", "h0", ">=", "h1", "h0", "-", "h1", "else", "if", "dst_offset", "=", "TimeUtil", ".", "dst_change", "(", "time", ")", "h0", "-", "h1", "+", "dst_offset", "else", "24", "-", "h1", "+", "h0", "end", "end", "end" ]
Lock the hour if explicitly set by hour_of_day, but allow for the nearest hour during DST start to keep the correct interval.
[ "Lock", "the", "hour", "if", "explicitly", "set", "by", "hour_of_day", "but", "allow", "for", "the", "nearest", "hour", "during", "DST", "start", "to", "keep", "the", "correct", "interval", "." ]
fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd
https://github.com/seejohnrun/ice_cube/blob/fb6c657bdc4f87dfda2bf83f15c5f487b78ccabd/lib/ice_cube/validations/fixed_value.rb#L37-L49