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
partition
stringclasses
1 value
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.get_innings
def get_innings if @innings.length == 0 inn_count = get_num_innings (1..get_num_innings).each do |inn| inning = Inning.new inning.load_from_id(@gid, inn) @innings << inning end end @innings end
ruby
def get_innings if @innings.length == 0 inn_count = get_num_innings (1..get_num_innings).each do |inn| inning = Inning.new inning.load_from_id(@gid, inn) @innings << inning end end @innings end
[ "def", "get_innings", "if", "@innings", ".", "length", "==", "0", "inn_count", "=", "get_num_innings", "(", "1", "..", "get_num_innings", ")", ".", "each", "do", "|", "inn", "|", "inning", "=", "Inning", ".", "new", "inning", ".", "load_from_id", "(", "@gid", ",", "inn", ")", "@innings", "<<", "inning", "end", "end", "@innings", "end" ]
Returns an array of Inning objects that represent each inning of the game
[ "Returns", "an", "array", "of", "Inning", "objects", "that", "represent", "each", "inning", "of", "the", "game" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L430-L440
train
timothyf/gameday_api
lib/gameday_api/game.rb
GamedayApi.Game.get_atbats
def get_atbats atbats = [] innings = get_innings innings.each do |inning| inning.top_atbats.each do |atbat| atbats << atbat end inning.bottom_atbats.each do |atbat| atbats << atbat end end atbats end
ruby
def get_atbats atbats = [] innings = get_innings innings.each do |inning| inning.top_atbats.each do |atbat| atbats << atbat end inning.bottom_atbats.each do |atbat| atbats << atbat end end atbats end
[ "def", "get_atbats", "atbats", "=", "[", "]", "innings", "=", "get_innings", "innings", ".", "each", "do", "|", "inning", "|", "inning", ".", "top_atbats", ".", "each", "do", "|", "atbat", "|", "atbats", "<<", "atbat", "end", "inning", ".", "bottom_atbats", ".", "each", "do", "|", "atbat", "|", "atbats", "<<", "atbat", "end", "end", "atbats", "end" ]
Returns an array of AtBat objects that represent each atbat of the game
[ "Returns", "an", "array", "of", "AtBat", "objects", "that", "represent", "each", "atbat", "of", "the", "game" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/game.rb#L444-L456
train
timothyf/gameday_api
lib/gameday_api/line_score.rb
GamedayApi.LineScore.init
def init(element) @xml_doc = element self.away_team_runs = element.attributes["away_team_runs"] self.away_team_hits = element.attributes["away_team_hits"] self.away_team_errors = element.attributes["away_team_errors"] self.home_team_runs = element.attributes["home_team_runs"] self.home_team_hits = element.attributes["home_team_hits"] self.home_team_errors = element.attributes["home_team_errors"] # Set score by innings set_innings end
ruby
def init(element) @xml_doc = element self.away_team_runs = element.attributes["away_team_runs"] self.away_team_hits = element.attributes["away_team_hits"] self.away_team_errors = element.attributes["away_team_errors"] self.home_team_runs = element.attributes["home_team_runs"] self.home_team_hits = element.attributes["home_team_hits"] self.home_team_errors = element.attributes["home_team_errors"] # Set score by innings set_innings end
[ "def", "init", "(", "element", ")", "@xml_doc", "=", "element", "self", ".", "away_team_runs", "=", "element", ".", "attributes", "[", "\"away_team_runs\"", "]", "self", ".", "away_team_hits", "=", "element", ".", "attributes", "[", "\"away_team_hits\"", "]", "self", ".", "away_team_errors", "=", "element", ".", "attributes", "[", "\"away_team_errors\"", "]", "self", ".", "home_team_runs", "=", "element", ".", "attributes", "[", "\"home_team_runs\"", "]", "self", ".", "home_team_hits", "=", "element", ".", "attributes", "[", "\"home_team_hits\"", "]", "self", ".", "home_team_errors", "=", "element", ".", "attributes", "[", "\"home_team_errors\"", "]", "set_innings", "end" ]
Initialize this instance from an XML element containing linescore data.
[ "Initialize", "this", "instance", "from", "an", "XML", "element", "containing", "linescore", "data", "." ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/line_score.rb#L11-L23
train
timothyf/gameday_api
lib/gameday_api/batting_appearance.rb
GamedayApi.BattingAppearance.get_player
def get_player if !self.player # retrieve player object player = Player.new player.init() self.player = player end self.player end
ruby
def get_player if !self.player # retrieve player object player = Player.new player.init() self.player = player end self.player end
[ "def", "get_player", "if", "!", "self", ".", "player", "player", "=", "Player", ".", "new", "player", ".", "init", "(", ")", "self", ".", "player", "=", "player", "end", "self", ".", "player", "end" ]
Looks up the player record using the players.xml file for the player in this appearance
[ "Looks", "up", "the", "player", "record", "using", "the", "players", ".", "xml", "file", "for", "the", "player", "in", "this", "appearance" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/batting_appearance.rb#L42-L50
train
timothyf/gameday_api
lib/gameday_api/inning.rb
GamedayApi.Inning.load_from_id
def load_from_id(gid, inning) @top_atbats = [] @bottom_atbats = [] @gid = gid begin @xml_data = GamedayFetcher.fetch_inningx(gid, inning) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root @num = @xml_doc.root.attributes["num"] @away_team = @xml_doc.root.attributes["away_team"] @home_team = @xml_doc.root.attributes["home_team"] set_top_ab set_bottom_ab end rescue puts "Could not load inning file for #{gid}, inning #{inning.to_s}" end end
ruby
def load_from_id(gid, inning) @top_atbats = [] @bottom_atbats = [] @gid = gid begin @xml_data = GamedayFetcher.fetch_inningx(gid, inning) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root @num = @xml_doc.root.attributes["num"] @away_team = @xml_doc.root.attributes["away_team"] @home_team = @xml_doc.root.attributes["home_team"] set_top_ab set_bottom_ab end rescue puts "Could not load inning file for #{gid}, inning #{inning.to_s}" end end
[ "def", "load_from_id", "(", "gid", ",", "inning", ")", "@top_atbats", "=", "[", "]", "@bottom_atbats", "=", "[", "]", "@gid", "=", "gid", "begin", "@xml_data", "=", "GamedayFetcher", ".", "fetch_inningx", "(", "gid", ",", "inning", ")", "@xml_doc", "=", "REXML", "::", "Document", ".", "new", "(", "@xml_data", ")", "if", "@xml_doc", ".", "root", "@num", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"num\"", "]", "@away_team", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"away_team\"", "]", "@home_team", "=", "@xml_doc", ".", "root", ".", "attributes", "[", "\"home_team\"", "]", "set_top_ab", "set_bottom_ab", "end", "rescue", "puts", "\"Could not load inning file for #{gid}, inning #{inning.to_s}\"", "end", "end" ]
loads an Inning object given a game id and an inning number
[ "loads", "an", "Inning", "object", "given", "a", "game", "id", "and", "an", "inning", "number" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/inning.rb#L13-L30
train
timothyf/gameday_api
lib/gameday_api/roster.rb
GamedayApi.Roster.init
def init(element, gid) self.gid = gid self.team_name = element.attributes['name'] self.id = element.attributes['id'] self.type = element.attributes['type'] self.players = [] self.coaches = [] self.set_players(element) self.set_coaches(element) end
ruby
def init(element, gid) self.gid = gid self.team_name = element.attributes['name'] self.id = element.attributes['id'] self.type = element.attributes['type'] self.players = [] self.coaches = [] self.set_players(element) self.set_coaches(element) end
[ "def", "init", "(", "element", ",", "gid", ")", "self", ".", "gid", "=", "gid", "self", ".", "team_name", "=", "element", ".", "attributes", "[", "'name'", "]", "self", ".", "id", "=", "element", ".", "attributes", "[", "'id'", "]", "self", ".", "type", "=", "element", ".", "attributes", "[", "'type'", "]", "self", ".", "players", "=", "[", "]", "self", ".", "coaches", "=", "[", "]", "self", ".", "set_players", "(", "element", ")", "self", ".", "set_coaches", "(", "element", ")", "end" ]
type = home or away
[ "type", "=", "home", "or", "away" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/roster.rb#L13-L22
train
mcordell/grape_devise_token_auth
lib/grape_devise_token_auth/devise_interface.rb
GrapeDeviseTokenAuth.DeviseInterface.set_user_in_warden
def set_user_in_warden(scope, resource) scope = Devise::Mapping.find_scope!(scope) warden.set_user(resource, scope: scope, store: false) end
ruby
def set_user_in_warden(scope, resource) scope = Devise::Mapping.find_scope!(scope) warden.set_user(resource, scope: scope, store: false) end
[ "def", "set_user_in_warden", "(", "scope", ",", "resource", ")", "scope", "=", "Devise", "::", "Mapping", ".", "find_scope!", "(", "scope", ")", "warden", ".", "set_user", "(", "resource", ",", "scope", ":", "scope", ",", "store", ":", "false", ")", "end" ]
extracted and simplified from Devise
[ "extracted", "and", "simplified", "from", "Devise" ]
c5b1ead8dbad1dc9fa2a2e7c9346f167e1d9fb1f
https://github.com/mcordell/grape_devise_token_auth/blob/c5b1ead8dbad1dc9fa2a2e7c9346f167e1d9fb1f/lib/grape_devise_token_auth/devise_interface.rb#L9-L12
train
timothyf/gameday_api
lib/gameday_api/db_importer.rb
GamedayApi.DbImporter.import_team_for_month
def import_team_for_month(team_abbrev, year, month) start_date = Date.new(year.to_i, month.to_i) # first day of month end_date = (start_date >> 1)-1 # last day of month ((start_date)..(end_date)).each do |dt| puts year.to_s + '/' + month.to_s + '/' + dt.day team = Team.new('det') games = team.games_for_date(year, month, dt.day.to_s) games.each do |game| import_for_game(game.gid) end end end
ruby
def import_team_for_month(team_abbrev, year, month) start_date = Date.new(year.to_i, month.to_i) # first day of month end_date = (start_date >> 1)-1 # last day of month ((start_date)..(end_date)).each do |dt| puts year.to_s + '/' + month.to_s + '/' + dt.day team = Team.new('det') games = team.games_for_date(year, month, dt.day.to_s) games.each do |game| import_for_game(game.gid) end end end
[ "def", "import_team_for_month", "(", "team_abbrev", ",", "year", ",", "month", ")", "start_date", "=", "Date", ".", "new", "(", "year", ".", "to_i", ",", "month", ".", "to_i", ")", "end_date", "=", "(", "start_date", ">>", "1", ")", "-", "1", "(", "(", "start_date", ")", "..", "(", "end_date", ")", ")", ".", "each", "do", "|", "dt", "|", "puts", "year", ".", "to_s", "+", "'/'", "+", "month", ".", "to_s", "+", "'/'", "+", "dt", ".", "day", "team", "=", "Team", ".", "new", "(", "'det'", ")", "games", "=", "team", ".", "games_for_date", "(", "year", ",", "month", ",", "dt", ".", "day", ".", "to_s", ")", "games", ".", "each", "do", "|", "game", "|", "import_for_game", "(", "game", ".", "gid", ")", "end", "end", "end" ]
player team game atbat pitch pitch type game type umpire
[ "player", "team", "game", "atbat", "pitch", "pitch", "type", "game", "type", "umpire" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/db_importer.rb#L25-L36
train
puppetlabs/beaker-docker
lib/beaker/hypervisor/docker.rb
Beaker.Docker.install_ssh_components
def install_ssh_components(container, host) case host['platform'] when /ubuntu/, /debian/ container.exec(%w(apt-get update)) container.exec(%w(apt-get install -y openssh-server openssh-client)) when /cumulus/ container.exec(%w(apt-get update)) container.exec(%w(apt-get install -y openssh-server openssh-client)) when /fedora-(2[2-9])/ container.exec(%w(dnf clean all)) container.exec(%w(dnf install -y sudo openssh-server openssh-clients)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) when /^el-/, /centos/, /fedora/, /redhat/, /eos/ container.exec(%w(yum clean all)) container.exec(%w(yum install -y sudo openssh-server openssh-clients)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) when /opensuse/, /sles/ container.exec(%w(zypper -n in openssh)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config)) when /archlinux/ container.exec(%w(pacman --noconfirm -Sy archlinux-keyring)) container.exec(%w(pacman --noconfirm -Syu)) container.exec(%w(pacman -S --noconfirm openssh)) container.exec(%w(ssh-keygen -A)) container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config)) container.exec(%w(systemctl enable sshd)) when /alpine/ container.exec(%w(apk add --update openssh)) container.exec(%w(ssh-keygen -A)) else # TODO add more platform steps here raise "platform #{host['platform']} not yet supported on docker" end # Make sshd directory, set root password container.exec(%w(mkdir -p /var/run/sshd)) container.exec(['/bin/sh', '-c', "echo root:#{root_password} | chpasswd"]) end
ruby
def install_ssh_components(container, host) case host['platform'] when /ubuntu/, /debian/ container.exec(%w(apt-get update)) container.exec(%w(apt-get install -y openssh-server openssh-client)) when /cumulus/ container.exec(%w(apt-get update)) container.exec(%w(apt-get install -y openssh-server openssh-client)) when /fedora-(2[2-9])/ container.exec(%w(dnf clean all)) container.exec(%w(dnf install -y sudo openssh-server openssh-clients)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) when /^el-/, /centos/, /fedora/, /redhat/, /eos/ container.exec(%w(yum clean all)) container.exec(%w(yum install -y sudo openssh-server openssh-clients)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) when /opensuse/, /sles/ container.exec(%w(zypper -n in openssh)) container.exec(%w(ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key)) container.exec(%w(ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key)) container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config)) when /archlinux/ container.exec(%w(pacman --noconfirm -Sy archlinux-keyring)) container.exec(%w(pacman --noconfirm -Syu)) container.exec(%w(pacman -S --noconfirm openssh)) container.exec(%w(ssh-keygen -A)) container.exec(%w(sed -ri 's/^#?UsePAM .*/UsePAM no/' /etc/ssh/sshd_config)) container.exec(%w(systemctl enable sshd)) when /alpine/ container.exec(%w(apk add --update openssh)) container.exec(%w(ssh-keygen -A)) else # TODO add more platform steps here raise "platform #{host['platform']} not yet supported on docker" end # Make sshd directory, set root password container.exec(%w(mkdir -p /var/run/sshd)) container.exec(['/bin/sh', '-c', "echo root:#{root_password} | chpasswd"]) end
[ "def", "install_ssh_components", "(", "container", ",", "host", ")", "case", "host", "[", "'platform'", "]", "when", "/", "/", ",", "/", "/", "container", ".", "exec", "(", "%w(", "apt-get", "update", ")", ")", "container", ".", "exec", "(", "%w(", "apt-get", "install", "-y", "openssh-server", "openssh-client", ")", ")", "when", "/", "/", "container", ".", "exec", "(", "%w(", "apt-get", "update", ")", ")", "container", ".", "exec", "(", "%w(", "apt-get", "install", "-y", "openssh-server", "openssh-client", ")", ")", "when", "/", "/", "container", ".", "exec", "(", "%w(", "dnf", "clean", "all", ")", ")", "container", ".", "exec", "(", "%w(", "dnf", "install", "-y", "sudo", "openssh-server", "openssh-clients", ")", ")", "container", ".", "exec", "(", "%w(", "ssh-keygen", "-t", "rsa", "-f", "/etc/ssh/ssh_host_rsa_key", ")", ")", "container", ".", "exec", "(", "%w(", "ssh-keygen", "-t", "dsa", "-f", "/etc/ssh/ssh_host_dsa_key", ")", ")", "when", "/", "/", ",", "/", "/", ",", "/", "/", ",", "/", "/", ",", "/", "/", "container", ".", "exec", "(", "%w(", "yum", "clean", "all", ")", ")", "container", ".", "exec", "(", "%w(", "yum", "install", "-y", "sudo", "openssh-server", "openssh-clients", ")", ")", "container", ".", "exec", "(", "%w(", "ssh-keygen", "-t", "rsa", "-f", "/etc/ssh/ssh_host_rsa_key", ")", ")", "container", ".", "exec", "(", "%w(", "ssh-keygen", "-t", "dsa", "-f", "/etc/ssh/ssh_host_dsa_key", ")", ")", "when", "/", "/", ",", "/", "/", "container", ".", "exec", "(", "%w(", "zypper", "-n", "in", "openssh", ")", ")", "container", ".", "exec", "(", "%w(", "ssh-keygen", "-t", "rsa", "-f", "/etc/ssh/ssh_host_rsa_key", ")", ")", "container", ".", "exec", "(", "%w(", "ssh-keygen", "-t", "dsa", "-f", "/etc/ssh/ssh_host_dsa_key", ")", ")", "container", ".", "exec", "(", "%w(", "sed", "-ri", "'s/^#?UsePAM", ".*/UsePAM", "no/'", "/etc/ssh/sshd_config", ")", ")", "when", "/", "/", "container", ".", "exec", "(", "%w(", "pacman", "--noconfirm", "-Sy", "archlinux-keyring", ")", ")", "container", ".", "exec", "(", "%w(", "pacman", "--noconfirm", "-Syu", ")", ")", "container", ".", "exec", "(", "%w(", "pacman", "-S", "--noconfirm", "openssh", ")", ")", "container", ".", "exec", "(", "%w(", "ssh-keygen", "-A", ")", ")", "container", ".", "exec", "(", "%w(", "sed", "-ri", "'s/^#?UsePAM", ".*/UsePAM", "no/'", "/etc/ssh/sshd_config", ")", ")", "container", ".", "exec", "(", "%w(", "systemctl", "enable", "sshd", ")", ")", "when", "/", "/", "container", ".", "exec", "(", "%w(", "apk", "add", "--update", "openssh", ")", ")", "container", ".", "exec", "(", "%w(", "ssh-keygen", "-A", ")", ")", "else", "raise", "\"platform #{host['platform']} not yet supported on docker\"", "end", "container", ".", "exec", "(", "%w(", "mkdir", "-p", "/var/run/sshd", ")", ")", "container", ".", "exec", "(", "[", "'/bin/sh'", ",", "'-c'", ",", "\"echo root:#{root_password} | chpasswd\"", "]", ")", "end" ]
This sideloads sshd after a container starts
[ "This", "sideloads", "sshd", "after", "a", "container", "starts" ]
d102f4af3af7d2231a5f43fbeaa57379cdcf825b
https://github.com/puppetlabs/beaker-docker/blob/d102f4af3af7d2231a5f43fbeaa57379cdcf825b/lib/beaker/hypervisor/docker.rb#L221-L262
train
puppetlabs/beaker-docker
lib/beaker/hypervisor/docker.rb
Beaker.Docker.fix_ssh
def fix_ssh(container, host=nil) @logger.debug("Fixing ssh on container #{container.id}") container.exec(['sed','-ri', 's/^#?PermitRootLogin .*/PermitRootLogin yes/', '/etc/ssh/sshd_config']) container.exec(['sed','-ri', 's/^#?PasswordAuthentication .*/PasswordAuthentication yes/', '/etc/ssh/sshd_config']) container.exec(['sed','-ri', 's/^#?UseDNS .*/UseDNS no/', '/etc/ssh/sshd_config']) # Make sure users with a bunch of SSH keys loaded in their keyring can # still run tests container.exec(['sed','-ri', 's/^#?MaxAuthTries.*/MaxAuthTries 1000/', '/etc/ssh/sshd_config']) if host if host['platform'] =~ /alpine/ container.exec(%w(/usr/sbin/sshd)) else container.exec(%w(service ssh restart)) end end end
ruby
def fix_ssh(container, host=nil) @logger.debug("Fixing ssh on container #{container.id}") container.exec(['sed','-ri', 's/^#?PermitRootLogin .*/PermitRootLogin yes/', '/etc/ssh/sshd_config']) container.exec(['sed','-ri', 's/^#?PasswordAuthentication .*/PasswordAuthentication yes/', '/etc/ssh/sshd_config']) container.exec(['sed','-ri', 's/^#?UseDNS .*/UseDNS no/', '/etc/ssh/sshd_config']) # Make sure users with a bunch of SSH keys loaded in their keyring can # still run tests container.exec(['sed','-ri', 's/^#?MaxAuthTries.*/MaxAuthTries 1000/', '/etc/ssh/sshd_config']) if host if host['platform'] =~ /alpine/ container.exec(%w(/usr/sbin/sshd)) else container.exec(%w(service ssh restart)) end end end
[ "def", "fix_ssh", "(", "container", ",", "host", "=", "nil", ")", "@logger", ".", "debug", "(", "\"Fixing ssh on container #{container.id}\"", ")", "container", ".", "exec", "(", "[", "'sed'", ",", "'-ri'", ",", "'s/^#?PermitRootLogin .*/PermitRootLogin yes/'", ",", "'/etc/ssh/sshd_config'", "]", ")", "container", ".", "exec", "(", "[", "'sed'", ",", "'-ri'", ",", "'s/^#?PasswordAuthentication .*/PasswordAuthentication yes/'", ",", "'/etc/ssh/sshd_config'", "]", ")", "container", ".", "exec", "(", "[", "'sed'", ",", "'-ri'", ",", "'s/^#?UseDNS .*/UseDNS no/'", ",", "'/etc/ssh/sshd_config'", "]", ")", "container", ".", "exec", "(", "[", "'sed'", ",", "'-ri'", ",", "'s/^#?MaxAuthTries.*/MaxAuthTries 1000/'", ",", "'/etc/ssh/sshd_config'", "]", ")", "if", "host", "if", "host", "[", "'platform'", "]", "=~", "/", "/", "container", ".", "exec", "(", "%w(", "/usr/sbin/sshd", ")", ")", "else", "container", ".", "exec", "(", "%w(", "service", "ssh", "restart", ")", ")", "end", "end", "end" ]
a puppet run may have changed the ssh config which would keep us out of the container. This is a best effort to fix it. Optionally pass in a host object to to determine which ssh restart command we should try.
[ "a", "puppet", "run", "may", "have", "changed", "the", "ssh", "config", "which", "would", "keep", "us", "out", "of", "the", "container", ".", "This", "is", "a", "best", "effort", "to", "fix", "it", ".", "Optionally", "pass", "in", "a", "host", "object", "to", "to", "determine", "which", "ssh", "restart", "command", "we", "should", "try", "." ]
d102f4af3af7d2231a5f43fbeaa57379cdcf825b
https://github.com/puppetlabs/beaker-docker/blob/d102f4af3af7d2231a5f43fbeaa57379cdcf825b/lib/beaker/hypervisor/docker.rb#L436-L460
train
puppetlabs/beaker-docker
lib/beaker/hypervisor/docker.rb
Beaker.Docker.find_container
def find_container(host) id = host['docker_container_id'] name = host['docker_container_name'] return unless id || name containers = ::Docker::Container.all if id @logger.debug("Looking for an existing container with ID #{id}") container = containers.select { |c| c.id == id }.first end if name && container.nil? @logger.debug("Looking for an existing container with name #{name}") container = containers.select do |c| c.info['Names'].include? "/#{name}" end.first end return container unless container.nil? @logger.debug("Existing container not found") end
ruby
def find_container(host) id = host['docker_container_id'] name = host['docker_container_name'] return unless id || name containers = ::Docker::Container.all if id @logger.debug("Looking for an existing container with ID #{id}") container = containers.select { |c| c.id == id }.first end if name && container.nil? @logger.debug("Looking for an existing container with name #{name}") container = containers.select do |c| c.info['Names'].include? "/#{name}" end.first end return container unless container.nil? @logger.debug("Existing container not found") end
[ "def", "find_container", "(", "host", ")", "id", "=", "host", "[", "'docker_container_id'", "]", "name", "=", "host", "[", "'docker_container_name'", "]", "return", "unless", "id", "||", "name", "containers", "=", "::", "Docker", "::", "Container", ".", "all", "if", "id", "@logger", ".", "debug", "(", "\"Looking for an existing container with ID #{id}\"", ")", "container", "=", "containers", ".", "select", "{", "|", "c", "|", "c", ".", "id", "==", "id", "}", ".", "first", "end", "if", "name", "&&", "container", ".", "nil?", "@logger", ".", "debug", "(", "\"Looking for an existing container with name #{name}\"", ")", "container", "=", "containers", ".", "select", "do", "|", "c", "|", "c", ".", "info", "[", "'Names'", "]", ".", "include?", "\"/#{name}\"", "end", ".", "first", "end", "return", "container", "unless", "container", ".", "nil?", "@logger", ".", "debug", "(", "\"Existing container not found\"", ")", "end" ]
return the existing container if we're not provisioning and docker_container_name is set
[ "return", "the", "existing", "container", "if", "we", "re", "not", "provisioning", "and", "docker_container_name", "is", "set" ]
d102f4af3af7d2231a5f43fbeaa57379cdcf825b
https://github.com/puppetlabs/beaker-docker/blob/d102f4af3af7d2231a5f43fbeaa57379cdcf825b/lib/beaker/hypervisor/docker.rb#L465-L486
train
timothyf/gameday_api
lib/gameday_api/players.rb
GamedayApi.Players.load_from_id
def load_from_id(gid) @gid = gid @rosters = [] @umpires = {} @xml_data = GamedayFetcher.fetch_players(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root self.set_rosters self.set_umpires end end
ruby
def load_from_id(gid) @gid = gid @rosters = [] @umpires = {} @xml_data = GamedayFetcher.fetch_players(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root self.set_rosters self.set_umpires end end
[ "def", "load_from_id", "(", "gid", ")", "@gid", "=", "gid", "@rosters", "=", "[", "]", "@umpires", "=", "{", "}", "@xml_data", "=", "GamedayFetcher", ".", "fetch_players", "(", "gid", ")", "@xml_doc", "=", "REXML", "::", "Document", ".", "new", "(", "@xml_data", ")", "if", "@xml_doc", ".", "root", "self", ".", "set_rosters", "self", ".", "set_umpires", "end", "end" ]
Loads the players XML from the MLB gameday server and parses it using REXML
[ "Loads", "the", "players", "XML", "from", "the", "MLB", "gameday", "server", "and", "parses", "it", "using", "REXML" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/players.rb#L12-L22
train
timothyf/gameday_api
lib/gameday_api/pitchfx_db_manager.rb
GamedayApi.PitchfxDbManager.update_rosters
def update_rosters(game, away_id, home_id) game_id = find_or_create_game(game, nil, nil) gameday_info = GamedayUtil.parse_gameday_id('gid_' + game.gid) active_date = "#{gameday_info['year']}/#{gameday_info['month']}/#{gameday_info['day']}" away_res = @db.query("select id from rosters where team_id = '#{away_id}' and active_date = '#{active_date}'") away_roster_id=0 found = false away_res.each do |row| found = true away_roster_id = row['id'] end @db.query("UPDATE rosters SET game_id = '#{game_id}', home_or_away = 'a' WHERE id = '#{away_roster_id}'") home_res = @db.query("select id from rosters where team_id = '#{home_id}' and active_date = '#{active_date}'") home_roster_id=0 found = false home_res.each do |row| found = true home_roster_id = row['id'] end @db.query("UPDATE rosters SET game_id = '#{game_id}', home_or_away = 'h' WHERE id = '#{home_roster_id}'") end
ruby
def update_rosters(game, away_id, home_id) game_id = find_or_create_game(game, nil, nil) gameday_info = GamedayUtil.parse_gameday_id('gid_' + game.gid) active_date = "#{gameday_info['year']}/#{gameday_info['month']}/#{gameday_info['day']}" away_res = @db.query("select id from rosters where team_id = '#{away_id}' and active_date = '#{active_date}'") away_roster_id=0 found = false away_res.each do |row| found = true away_roster_id = row['id'] end @db.query("UPDATE rosters SET game_id = '#{game_id}', home_or_away = 'a' WHERE id = '#{away_roster_id}'") home_res = @db.query("select id from rosters where team_id = '#{home_id}' and active_date = '#{active_date}'") home_roster_id=0 found = false home_res.each do |row| found = true home_roster_id = row['id'] end @db.query("UPDATE rosters SET game_id = '#{game_id}', home_or_away = 'h' WHERE id = '#{home_roster_id}'") end
[ "def", "update_rosters", "(", "game", ",", "away_id", ",", "home_id", ")", "game_id", "=", "find_or_create_game", "(", "game", ",", "nil", ",", "nil", ")", "gameday_info", "=", "GamedayUtil", ".", "parse_gameday_id", "(", "'gid_'", "+", "game", ".", "gid", ")", "active_date", "=", "\"#{gameday_info['year']}/#{gameday_info['month']}/#{gameday_info['day']}\"", "away_res", "=", "@db", ".", "query", "(", "\"select id from rosters where team_id = '#{away_id}' and active_date = '#{active_date}'\"", ")", "away_roster_id", "=", "0", "found", "=", "false", "away_res", ".", "each", "do", "|", "row", "|", "found", "=", "true", "away_roster_id", "=", "row", "[", "'id'", "]", "end", "@db", ".", "query", "(", "\"UPDATE rosters SET game_id = '#{game_id}', home_or_away = 'a' WHERE id = '#{away_roster_id}'\"", ")", "home_res", "=", "@db", ".", "query", "(", "\"select id from rosters where team_id = '#{home_id}' and active_date = '#{active_date}'\"", ")", "home_roster_id", "=", "0", "found", "=", "false", "home_res", ".", "each", "do", "|", "row", "|", "found", "=", "true", "home_roster_id", "=", "row", "[", "'id'", "]", "end", "@db", ".", "query", "(", "\"UPDATE rosters SET game_id = '#{game_id}', home_or_away = 'h' WHERE id = '#{home_roster_id}'\"", ")", "end" ]
Used to set game_id and home_or_away flag
[ "Used", "to", "set", "game_id", "and", "home_or_away", "flag" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/pitchfx_db_manager.rb#L460-L488
train
timothyf/gameday_api
lib/gameday_api/pitchfx_db_manager.rb
GamedayApi.PitchfxDbManager.update_umpire_ids_for_games
def update_umpire_ids_for_games ump_id_hp = nil ump_id_1b = nil ump_id_2b = nil ump_id_3b = nil res = @db.query("select id, umpire_hp_id, umpire_1b_id, umpire_2b_id, umpire_3b_id from games") res.each do |row| # each game game_id = row[0] umpire_hp_id = row['umpire_hp_id'] umpire_1b_id = row['umpire_1b_id'] umpire_2b_id = row['umpire_2b_id'] umpire_3b_id = row['umpire_3b_id'] # look up umpire record for hp ump ump_id_hp = get_first_occurance_of_umpire(umpire_hp_id) ump_id_1b = get_first_occurance_of_umpire(umpire_1b_id) ump_id_2b = get_first_occurance_of_umpire(umpire_2b_id) ump_id_3b = get_first_occurance_of_umpire(umpire_3b_id) # update game with correct ump ids @db.query("UPDATE games SET umpire_hp_id='#{ump_id_hp}',umpire_1b_id='#{ump_id_1b}', umpire_2b_id='#{ump_id_2b}', umpire_3b_id='#{ump_id_3b}' WHERE id=#{game_id}") end end
ruby
def update_umpire_ids_for_games ump_id_hp = nil ump_id_1b = nil ump_id_2b = nil ump_id_3b = nil res = @db.query("select id, umpire_hp_id, umpire_1b_id, umpire_2b_id, umpire_3b_id from games") res.each do |row| # each game game_id = row[0] umpire_hp_id = row['umpire_hp_id'] umpire_1b_id = row['umpire_1b_id'] umpire_2b_id = row['umpire_2b_id'] umpire_3b_id = row['umpire_3b_id'] # look up umpire record for hp ump ump_id_hp = get_first_occurance_of_umpire(umpire_hp_id) ump_id_1b = get_first_occurance_of_umpire(umpire_1b_id) ump_id_2b = get_first_occurance_of_umpire(umpire_2b_id) ump_id_3b = get_first_occurance_of_umpire(umpire_3b_id) # update game with correct ump ids @db.query("UPDATE games SET umpire_hp_id='#{ump_id_hp}',umpire_1b_id='#{ump_id_1b}', umpire_2b_id='#{ump_id_2b}', umpire_3b_id='#{ump_id_3b}' WHERE id=#{game_id}") end end
[ "def", "update_umpire_ids_for_games", "ump_id_hp", "=", "nil", "ump_id_1b", "=", "nil", "ump_id_2b", "=", "nil", "ump_id_3b", "=", "nil", "res", "=", "@db", ".", "query", "(", "\"select id, umpire_hp_id, umpire_1b_id, umpire_2b_id, umpire_3b_id from games\"", ")", "res", ".", "each", "do", "|", "row", "|", "game_id", "=", "row", "[", "0", "]", "umpire_hp_id", "=", "row", "[", "'umpire_hp_id'", "]", "umpire_1b_id", "=", "row", "[", "'umpire_1b_id'", "]", "umpire_2b_id", "=", "row", "[", "'umpire_2b_id'", "]", "umpire_3b_id", "=", "row", "[", "'umpire_3b_id'", "]", "ump_id_hp", "=", "get_first_occurance_of_umpire", "(", "umpire_hp_id", ")", "ump_id_1b", "=", "get_first_occurance_of_umpire", "(", "umpire_1b_id", ")", "ump_id_2b", "=", "get_first_occurance_of_umpire", "(", "umpire_2b_id", ")", "ump_id_3b", "=", "get_first_occurance_of_umpire", "(", "umpire_3b_id", ")", "@db", ".", "query", "(", "\"UPDATE games SET umpire_hp_id='#{ump_id_hp}',umpire_1b_id='#{ump_id_1b}',\r umpire_2b_id='#{ump_id_2b}', umpire_3b_id='#{ump_id_3b}' WHERE id=#{game_id}\"", ")", "end", "end" ]
Update the game records to point to the first instance of the specific umpires originally new umpire records were being inserted for every game, which is what caused this problem
[ "Update", "the", "game", "records", "to", "point", "to", "the", "first", "instance", "of", "the", "specific", "umpires", "originally", "new", "umpire", "records", "were", "being", "inserted", "for", "every", "game", "which", "is", "what", "caused", "this", "problem" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/pitchfx_db_manager.rb#L778-L801
train
timothyf/gameday_api
lib/gameday_api/event_log.rb
GamedayApi.EventLog.load_from_id
def load_from_id(gid) @gid = gid @xml_data = GamedayFetcher.fetch_eventlog(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root set_teams set_events end end
ruby
def load_from_id(gid) @gid = gid @xml_data = GamedayFetcher.fetch_eventlog(gid) @xml_doc = REXML::Document.new(@xml_data) if @xml_doc.root set_teams set_events end end
[ "def", "load_from_id", "(", "gid", ")", "@gid", "=", "gid", "@xml_data", "=", "GamedayFetcher", ".", "fetch_eventlog", "(", "gid", ")", "@xml_doc", "=", "REXML", "::", "Document", ".", "new", "(", "@xml_data", ")", "if", "@xml_doc", ".", "root", "set_teams", "set_events", "end", "end" ]
Loads the eventLog XML from the MLB gameday server and parses it using REXML
[ "Loads", "the", "eventLog", "XML", "from", "the", "MLB", "gameday", "server", "and", "parses", "it", "using", "REXML" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/event_log.rb#L15-L23
train
timothyf/gameday_api
lib/gameday_api/event_log.rb
GamedayApi.EventLog.set_teams
def set_teams @xml_doc.elements.each("game/team[@home_team='false']") do |element| @away_team = element.attributes["name"] end @xml_doc.elements.each("game/team[@home_team='true']") do |element| @home_team = element.attributes["name"] end end
ruby
def set_teams @xml_doc.elements.each("game/team[@home_team='false']") do |element| @away_team = element.attributes["name"] end @xml_doc.elements.each("game/team[@home_team='true']") do |element| @home_team = element.attributes["name"] end end
[ "def", "set_teams", "@xml_doc", ".", "elements", ".", "each", "(", "\"game/team[@home_team='false']\"", ")", "do", "|", "element", "|", "@away_team", "=", "element", ".", "attributes", "[", "\"name\"", "]", "end", "@xml_doc", ".", "elements", ".", "each", "(", "\"game/team[@home_team='true']\"", ")", "do", "|", "element", "|", "@home_team", "=", "element", ".", "attributes", "[", "\"name\"", "]", "end", "end" ]
Sets the team names for the teams involved in this game
[ "Sets", "the", "team", "names", "for", "the", "teams", "involved", "in", "this", "game" ]
2cb629398221f94ffadcaee35fe9740ee30577d4
https://github.com/timothyf/gameday_api/blob/2cb629398221f94ffadcaee35fe9740ee30577d4/lib/gameday_api/event_log.rb#L27-L34
train
chriskite/jimson
lib/jimson/server.rb
Jimson.Server.call
def call(env) req = Rack::Request.new(env) resp = Rack::Response.new return resp.finish if !req.post? resp.write process(req.body.read) resp.finish end
ruby
def call(env) req = Rack::Request.new(env) resp = Rack::Response.new return resp.finish if !req.post? resp.write process(req.body.read) resp.finish end
[ "def", "call", "(", "env", ")", "req", "=", "Rack", "::", "Request", ".", "new", "(", "env", ")", "resp", "=", "Rack", "::", "Response", ".", "new", "return", "resp", ".", "finish", "if", "!", "req", ".", "post?", "resp", ".", "write", "process", "(", "req", ".", "body", ".", "read", ")", "resp", ".", "finish", "end" ]
Entry point for Rack
[ "Entry", "point", "for", "Rack" ]
d921a29857384997509e477e655d152377a4dfcc
https://github.com/chriskite/jimson/blob/d921a29857384997509e477e655d152377a4dfcc/lib/jimson/server.rb#L83-L89
train
logdna/ruby
lib/logdna/client.rb
Logdna.Client.buffer
def buffer(msg, opts) buffer_size = write_to_buffer(msg, opts) unless buffer_size.nil? process_buffer(buffer_size) end end
ruby
def buffer(msg, opts) buffer_size = write_to_buffer(msg, opts) unless buffer_size.nil? process_buffer(buffer_size) end end
[ "def", "buffer", "(", "msg", ",", "opts", ")", "buffer_size", "=", "write_to_buffer", "(", "msg", ",", "opts", ")", "unless", "buffer_size", ".", "nil?", "process_buffer", "(", "buffer_size", ")", "end", "end" ]
this should always be running synchronously within this thread
[ "this", "should", "always", "be", "running", "synchronously", "within", "this", "thread" ]
8655d45d58f1d4fbf01e12e83bd9b37e8afc8614
https://github.com/logdna/ruby/blob/8655d45d58f1d4fbf01e12e83bd9b37e8afc8614/lib/logdna/client.rb#L86-L91
train
logdna/ruby
lib/logdna/client.rb
Logdna.Client.flush
def flush() if defined? @@request and !@@request.nil? request_messages = [] @lock.synchronize do request_messages = @messages @buffer.truncate(0) @messages = [] end return if request_messages.empty? real = { e: 'ls', ls: request_messages, }.to_json @@request.body = real @response = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: @uri.scheme == 'https') do |http| http.request(@@request) end # don't kill @task if this was executed from self.buffer # don't kill @task if there are queued messages unless @buffer_over_limit || @messages.any? || @task.nil? @task.shutdown @task.kill end end end
ruby
def flush() if defined? @@request and !@@request.nil? request_messages = [] @lock.synchronize do request_messages = @messages @buffer.truncate(0) @messages = [] end return if request_messages.empty? real = { e: 'ls', ls: request_messages, }.to_json @@request.body = real @response = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: @uri.scheme == 'https') do |http| http.request(@@request) end # don't kill @task if this was executed from self.buffer # don't kill @task if there are queued messages unless @buffer_over_limit || @messages.any? || @task.nil? @task.shutdown @task.kill end end end
[ "def", "flush", "(", ")", "if", "defined?", "@@request", "and", "!", "@@request", ".", "nil?", "request_messages", "=", "[", "]", "@lock", ".", "synchronize", "do", "request_messages", "=", "@messages", "@buffer", ".", "truncate", "(", "0", ")", "@messages", "=", "[", "]", "end", "return", "if", "request_messages", ".", "empty?", "real", "=", "{", "e", ":", "'ls'", ",", "ls", ":", "request_messages", ",", "}", ".", "to_json", "@@request", ".", "body", "=", "real", "@response", "=", "Net", "::", "HTTP", ".", "start", "(", "@uri", ".", "hostname", ",", "@uri", ".", "port", ",", "use_ssl", ":", "@uri", ".", "scheme", "==", "'https'", ")", "do", "|", "http", "|", "http", ".", "request", "(", "@@request", ")", "end", "unless", "@buffer_over_limit", "||", "@messages", ".", "any?", "||", "@task", ".", "nil?", "@task", ".", "shutdown", "@task", ".", "kill", "end", "end", "end" ]
this should be running synchronously if @buffer_over_limit i.e. called from self.buffer else asynchronously through @task
[ "this", "should", "be", "running", "synchronously", "if" ]
8655d45d58f1d4fbf01e12e83bd9b37e8afc8614
https://github.com/logdna/ruby/blob/8655d45d58f1d4fbf01e12e83bd9b37e8afc8614/lib/logdna/client.rb#L126-L153
train
pat/riddle
lib/riddle/client.rb
Riddle.Client.run
def run response = Response.new request(:search, @queue) results = @queue.collect do result = { :matches => [], :fields => [], :attributes => {}, :attribute_names => [], :words => {} } result[:status] = response.next_int case result[:status] when Statuses[:warning] result[:warning] = response.next when Statuses[:error] result[:error] = response.next next result end result[:fields] = response.next_array attributes = response.next_int attributes.times do attribute_name = response.next type = response.next_int result[:attributes][attribute_name] = type result[:attribute_names] << attribute_name end result_attribute_names_and_types = result[:attribute_names]. inject([]) { |array, attr| array.push([ attr, result[:attributes][attr] ]) } matches = response.next_int is_64_bit = response.next_int result[:matches] = (0...matches).map do |i| doc = is_64_bit > 0 ? response.next_64bit_int : response.next_int weight = response.next_int current_match_attributes = {} result_attribute_names_and_types.each do |attr, type| current_match_attributes[attr] = attribute_from_type(type, response) end {:doc => doc, :weight => weight, :index => i, :attributes => current_match_attributes} end result[:total] = response.next_int.to_i || 0 result[:total_found] = response.next_int.to_i || 0 result[:time] = ('%.3f' % (response.next_int / 1000.0)).to_f || 0.0 words = response.next_int words.times do word = response.next docs = response.next_int hits = response.next_int result[:words][word] = {:docs => docs, :hits => hits} end result end @queue.clear results rescue Riddle::OutOfBoundsError => error raise error rescue => original error = ResponseError.new original.message error.original = original raise error end
ruby
def run response = Response.new request(:search, @queue) results = @queue.collect do result = { :matches => [], :fields => [], :attributes => {}, :attribute_names => [], :words => {} } result[:status] = response.next_int case result[:status] when Statuses[:warning] result[:warning] = response.next when Statuses[:error] result[:error] = response.next next result end result[:fields] = response.next_array attributes = response.next_int attributes.times do attribute_name = response.next type = response.next_int result[:attributes][attribute_name] = type result[:attribute_names] << attribute_name end result_attribute_names_and_types = result[:attribute_names]. inject([]) { |array, attr| array.push([ attr, result[:attributes][attr] ]) } matches = response.next_int is_64_bit = response.next_int result[:matches] = (0...matches).map do |i| doc = is_64_bit > 0 ? response.next_64bit_int : response.next_int weight = response.next_int current_match_attributes = {} result_attribute_names_and_types.each do |attr, type| current_match_attributes[attr] = attribute_from_type(type, response) end {:doc => doc, :weight => weight, :index => i, :attributes => current_match_attributes} end result[:total] = response.next_int.to_i || 0 result[:total_found] = response.next_int.to_i || 0 result[:time] = ('%.3f' % (response.next_int / 1000.0)).to_f || 0.0 words = response.next_int words.times do word = response.next docs = response.next_int hits = response.next_int result[:words][word] = {:docs => docs, :hits => hits} end result end @queue.clear results rescue Riddle::OutOfBoundsError => error raise error rescue => original error = ResponseError.new original.message error.original = original raise error end
[ "def", "run", "response", "=", "Response", ".", "new", "request", "(", ":search", ",", "@queue", ")", "results", "=", "@queue", ".", "collect", "do", "result", "=", "{", ":matches", "=>", "[", "]", ",", ":fields", "=>", "[", "]", ",", ":attributes", "=>", "{", "}", ",", ":attribute_names", "=>", "[", "]", ",", ":words", "=>", "{", "}", "}", "result", "[", ":status", "]", "=", "response", ".", "next_int", "case", "result", "[", ":status", "]", "when", "Statuses", "[", ":warning", "]", "result", "[", ":warning", "]", "=", "response", ".", "next", "when", "Statuses", "[", ":error", "]", "result", "[", ":error", "]", "=", "response", ".", "next", "next", "result", "end", "result", "[", ":fields", "]", "=", "response", ".", "next_array", "attributes", "=", "response", ".", "next_int", "attributes", ".", "times", "do", "attribute_name", "=", "response", ".", "next", "type", "=", "response", ".", "next_int", "result", "[", ":attributes", "]", "[", "attribute_name", "]", "=", "type", "result", "[", ":attribute_names", "]", "<<", "attribute_name", "end", "result_attribute_names_and_types", "=", "result", "[", ":attribute_names", "]", ".", "inject", "(", "[", "]", ")", "{", "|", "array", ",", "attr", "|", "array", ".", "push", "(", "[", "attr", ",", "result", "[", ":attributes", "]", "[", "attr", "]", "]", ")", "}", "matches", "=", "response", ".", "next_int", "is_64_bit", "=", "response", ".", "next_int", "result", "[", ":matches", "]", "=", "(", "0", "...", "matches", ")", ".", "map", "do", "|", "i", "|", "doc", "=", "is_64_bit", ">", "0", "?", "response", ".", "next_64bit_int", ":", "response", ".", "next_int", "weight", "=", "response", ".", "next_int", "current_match_attributes", "=", "{", "}", "result_attribute_names_and_types", ".", "each", "do", "|", "attr", ",", "type", "|", "current_match_attributes", "[", "attr", "]", "=", "attribute_from_type", "(", "type", ",", "response", ")", "end", "{", ":doc", "=>", "doc", ",", ":weight", "=>", "weight", ",", ":index", "=>", "i", ",", ":attributes", "=>", "current_match_attributes", "}", "end", "result", "[", ":total", "]", "=", "response", ".", "next_int", ".", "to_i", "||", "0", "result", "[", ":total_found", "]", "=", "response", ".", "next_int", ".", "to_i", "||", "0", "result", "[", ":time", "]", "=", "(", "'%.3f'", "%", "(", "response", ".", "next_int", "/", "1000.0", ")", ")", ".", "to_f", "||", "0.0", "words", "=", "response", ".", "next_int", "words", ".", "times", "do", "word", "=", "response", ".", "next", "docs", "=", "response", ".", "next_int", "hits", "=", "response", ".", "next_int", "result", "[", ":words", "]", "[", "word", "]", "=", "{", ":docs", "=>", "docs", ",", ":hits", "=>", "hits", "}", "end", "result", "end", "@queue", ".", "clear", "results", "rescue", "Riddle", "::", "OutOfBoundsError", "=>", "error", "raise", "error", "rescue", "=>", "original", "error", "=", "ResponseError", ".", "new", "original", ".", "message", "error", ".", "original", "=", "original", "raise", "error", "end" ]
Run all the queries currently in the queue. This will return an array of results hashes.
[ "Run", "all", "the", "queries", "currently", "in", "the", "queue", ".", "This", "will", "return", "an", "array", "of", "results", "hashes", "." ]
4cd51cb37cc2c1000c9c1e873cef5109d291899e
https://github.com/pat/riddle/blob/4cd51cb37cc2c1000c9c1e873cef5109d291899e/lib/riddle/client.rb#L230-L304
train
pat/riddle
lib/riddle/client.rb
Riddle.Client.query
def query(search, index = '*', comments = '') @queue.clear @queue << query_message(search, index, comments) self.run.first end
ruby
def query(search, index = '*', comments = '') @queue.clear @queue << query_message(search, index, comments) self.run.first end
[ "def", "query", "(", "search", ",", "index", "=", "'*'", ",", "comments", "=", "''", ")", "@queue", ".", "clear", "@queue", "<<", "query_message", "(", "search", ",", "index", ",", "comments", ")", "self", ".", "run", ".", "first", "end" ]
Query the Sphinx daemon - defaulting to all indices, but you can specify a specific one if you wish. The search parameter should be a string following Sphinx's expectations. The object returned from this method is a hash with the following keys: * :matches * :fields * :attributes * :attribute_names * :words * :total * :total_found * :time * :status * :warning (if appropriate) * :error (if appropriate) The key <tt>:matches</tt> returns an array of hashes - the actual search results. Each hash has the document id (<tt>:doc</tt>), the result weighting (<tt>:weight</tt>), and a hash of the attributes for the document (<tt>:attributes</tt>). The <tt>:fields</tt> and <tt>:attribute_names</tt> keys return list of fields and attributes for the documents. The key <tt>:attributes</tt> will return a hash of attribute name and type pairs, and <tt>:words</tt> returns a hash of hashes representing the words from the search, with the number of documents and hits for each, along the lines of: results[:words]["Pat"] #=> {:docs => 12, :hits => 15} <tt>:total</tt>, <tt>:total_found</tt> and <tt>:time</tt> return the number of matches available, the total number of matches (which may be greater than the maximum available, depending on the number of matches and your sphinx configuration), and the time in milliseconds that the query took to run. <tt>:status</tt> is the error code for the query - and if there was a related warning, it will be under the <tt>:warning</tt> key. Fatal errors will be described under <tt>:error</tt>.
[ "Query", "the", "Sphinx", "daemon", "-", "defaulting", "to", "all", "indices", "but", "you", "can", "specify", "a", "specific", "one", "if", "you", "wish", ".", "The", "search", "parameter", "should", "be", "a", "string", "following", "Sphinx", "s", "expectations", "." ]
4cd51cb37cc2c1000c9c1e873cef5109d291899e
https://github.com/pat/riddle/blob/4cd51cb37cc2c1000c9c1e873cef5109d291899e/lib/riddle/client.rb#L347-L351
train
pat/riddle
lib/riddle/client.rb
Riddle.Client.update
def update(index, attributes, values_by_doc) response = Response.new request( :update, update_message(index, attributes, values_by_doc) ) response.next_int end
ruby
def update(index, attributes, values_by_doc) response = Response.new request( :update, update_message(index, attributes, values_by_doc) ) response.next_int end
[ "def", "update", "(", "index", ",", "attributes", ",", "values_by_doc", ")", "response", "=", "Response", ".", "new", "request", "(", ":update", ",", "update_message", "(", "index", ",", "attributes", ",", "values_by_doc", ")", ")", "response", ".", "next_int", "end" ]
Update attributes - first parameter is the relevant index, second is an array of attributes to be updated, and the third is a hash, where the keys are the document ids, and the values are arrays with the attribute values - in the same order as the second parameter. Example: client.update('people', ['birthday'], {1 => [Time.at(1982, 20, 8).to_i]})
[ "Update", "attributes", "-", "first", "parameter", "is", "the", "relevant", "index", "second", "is", "an", "array", "of", "attributes", "to", "be", "updated", "and", "the", "third", "is", "a", "hash", "where", "the", "keys", "are", "the", "document", "ids", "and", "the", "values", "are", "arrays", "with", "the", "attribute", "values", "-", "in", "the", "same", "order", "as", "the", "second", "parameter", "." ]
4cd51cb37cc2c1000c9c1e873cef5109d291899e
https://github.com/pat/riddle/blob/4cd51cb37cc2c1000c9c1e873cef5109d291899e/lib/riddle/client.rb#L433-L440
train
pat/riddle
lib/riddle/client.rb
Riddle.Client.query_message
def query_message(search, index, comments = '') message = Message.new # Mode, Limits message.append_ints @offset, @limit, MatchModes[@match_mode] # Ranking message.append_int RankModes[@rank_mode] message.append_string @rank_expr if @rank_mode == :expr # Sort Mode message.append_int SortModes[@sort_mode] message.append_string @sort_by # Query message.append_string search # Weights message.append_int @weights.length message.append_ints *@weights # Index message.append_string index # ID Range message.append_int 1 message.append_64bit_ints @id_range.first, @id_range.last # Filters message.append_int @filters.length @filters.each { |filter| message.append filter.query_message } # Grouping message.append_int GroupFunctions[@group_function] message.append_string @group_by message.append_int @max_matches message.append_string @group_clause message.append_ints @cut_off, @retry_count, @retry_delay message.append_string @group_distinct # Anchor Point if @anchor.empty? message.append_int 0 else message.append_int 1 message.append_string @anchor[:latitude_attribute] message.append_string @anchor[:longitude_attribute] message.append_floats @anchor[:latitude], @anchor[:longitude] end # Per Index Weights message.append_int @index_weights.length @index_weights.each do |key,val| message.append_string key.to_s message.append_int val end # Max Query Time message.append_int @max_query_time # Per Field Weights message.append_int @field_weights.length @field_weights.each do |key,val| message.append_string key.to_s message.append_int val end message.append_string comments return message.to_s if Versions[:search] < 0x116 # Overrides message.append_int @overrides.length @overrides.each do |key,val| message.append_string key.to_s message.append_int AttributeTypes[val[:type]] message.append_int val[:values].length val[:values].each do |id,map| message.append_64bit_int id method = case val[:type] when :float :append_float when :bigint :append_64bit_int else :append_int end message.send method, map end end message.append_string @select message.to_s end
ruby
def query_message(search, index, comments = '') message = Message.new # Mode, Limits message.append_ints @offset, @limit, MatchModes[@match_mode] # Ranking message.append_int RankModes[@rank_mode] message.append_string @rank_expr if @rank_mode == :expr # Sort Mode message.append_int SortModes[@sort_mode] message.append_string @sort_by # Query message.append_string search # Weights message.append_int @weights.length message.append_ints *@weights # Index message.append_string index # ID Range message.append_int 1 message.append_64bit_ints @id_range.first, @id_range.last # Filters message.append_int @filters.length @filters.each { |filter| message.append filter.query_message } # Grouping message.append_int GroupFunctions[@group_function] message.append_string @group_by message.append_int @max_matches message.append_string @group_clause message.append_ints @cut_off, @retry_count, @retry_delay message.append_string @group_distinct # Anchor Point if @anchor.empty? message.append_int 0 else message.append_int 1 message.append_string @anchor[:latitude_attribute] message.append_string @anchor[:longitude_attribute] message.append_floats @anchor[:latitude], @anchor[:longitude] end # Per Index Weights message.append_int @index_weights.length @index_weights.each do |key,val| message.append_string key.to_s message.append_int val end # Max Query Time message.append_int @max_query_time # Per Field Weights message.append_int @field_weights.length @field_weights.each do |key,val| message.append_string key.to_s message.append_int val end message.append_string comments return message.to_s if Versions[:search] < 0x116 # Overrides message.append_int @overrides.length @overrides.each do |key,val| message.append_string key.to_s message.append_int AttributeTypes[val[:type]] message.append_int val[:values].length val[:values].each do |id,map| message.append_64bit_int id method = case val[:type] when :float :append_float when :bigint :append_64bit_int else :append_int end message.send method, map end end message.append_string @select message.to_s end
[ "def", "query_message", "(", "search", ",", "index", ",", "comments", "=", "''", ")", "message", "=", "Message", ".", "new", "message", ".", "append_ints", "@offset", ",", "@limit", ",", "MatchModes", "[", "@match_mode", "]", "message", ".", "append_int", "RankModes", "[", "@rank_mode", "]", "message", ".", "append_string", "@rank_expr", "if", "@rank_mode", "==", ":expr", "message", ".", "append_int", "SortModes", "[", "@sort_mode", "]", "message", ".", "append_string", "@sort_by", "message", ".", "append_string", "search", "message", ".", "append_int", "@weights", ".", "length", "message", ".", "append_ints", "*", "@weights", "message", ".", "append_string", "index", "message", ".", "append_int", "1", "message", ".", "append_64bit_ints", "@id_range", ".", "first", ",", "@id_range", ".", "last", "message", ".", "append_int", "@filters", ".", "length", "@filters", ".", "each", "{", "|", "filter", "|", "message", ".", "append", "filter", ".", "query_message", "}", "message", ".", "append_int", "GroupFunctions", "[", "@group_function", "]", "message", ".", "append_string", "@group_by", "message", ".", "append_int", "@max_matches", "message", ".", "append_string", "@group_clause", "message", ".", "append_ints", "@cut_off", ",", "@retry_count", ",", "@retry_delay", "message", ".", "append_string", "@group_distinct", "if", "@anchor", ".", "empty?", "message", ".", "append_int", "0", "else", "message", ".", "append_int", "1", "message", ".", "append_string", "@anchor", "[", ":latitude_attribute", "]", "message", ".", "append_string", "@anchor", "[", ":longitude_attribute", "]", "message", ".", "append_floats", "@anchor", "[", ":latitude", "]", ",", "@anchor", "[", ":longitude", "]", "end", "message", ".", "append_int", "@index_weights", ".", "length", "@index_weights", ".", "each", "do", "|", "key", ",", "val", "|", "message", ".", "append_string", "key", ".", "to_s", "message", ".", "append_int", "val", "end", "message", ".", "append_int", "@max_query_time", "message", ".", "append_int", "@field_weights", ".", "length", "@field_weights", ".", "each", "do", "|", "key", ",", "val", "|", "message", ".", "append_string", "key", ".", "to_s", "message", ".", "append_int", "val", "end", "message", ".", "append_string", "comments", "return", "message", ".", "to_s", "if", "Versions", "[", ":search", "]", "<", "0x116", "message", ".", "append_int", "@overrides", ".", "length", "@overrides", ".", "each", "do", "|", "key", ",", "val", "|", "message", ".", "append_string", "key", ".", "to_s", "message", ".", "append_int", "AttributeTypes", "[", "val", "[", ":type", "]", "]", "message", ".", "append_int", "val", "[", ":values", "]", ".", "length", "val", "[", ":values", "]", ".", "each", "do", "|", "id", ",", "map", "|", "message", ".", "append_64bit_int", "id", "method", "=", "case", "val", "[", ":type", "]", "when", ":float", ":append_float", "when", ":bigint", ":append_64bit_int", "else", ":append_int", "end", "message", ".", "send", "method", ",", "map", "end", "end", "message", ".", "append_string", "@select", "message", ".", "to_s", "end" ]
Generation of the message to send to Sphinx for a search.
[ "Generation", "of", "the", "message", "to", "send", "to", "Sphinx", "for", "a", "search", "." ]
4cd51cb37cc2c1000c9c1e873cef5109d291899e
https://github.com/pat/riddle/blob/4cd51cb37cc2c1000c9c1e873cef5109d291899e/lib/riddle/client.rb#L695-L789
train
pat/riddle
lib/riddle/client.rb
Riddle.Client.excerpts_message
def excerpts_message(options) message = Message.new message.append [0, excerpt_flags(options)].pack('N2') # 0 = mode message.append_string options[:index] message.append_string options[:words] # options message.append_string options[:before_match] message.append_string options[:after_match] message.append_string options[:chunk_separator] message.append_ints options[:limit], options[:around] message.append_array options[:docs] message.to_s end
ruby
def excerpts_message(options) message = Message.new message.append [0, excerpt_flags(options)].pack('N2') # 0 = mode message.append_string options[:index] message.append_string options[:words] # options message.append_string options[:before_match] message.append_string options[:after_match] message.append_string options[:chunk_separator] message.append_ints options[:limit], options[:around] message.append_array options[:docs] message.to_s end
[ "def", "excerpts_message", "(", "options", ")", "message", "=", "Message", ".", "new", "message", ".", "append", "[", "0", ",", "excerpt_flags", "(", "options", ")", "]", ".", "pack", "(", "'N2'", ")", "message", ".", "append_string", "options", "[", ":index", "]", "message", ".", "append_string", "options", "[", ":words", "]", "message", ".", "append_string", "options", "[", ":before_match", "]", "message", ".", "append_string", "options", "[", ":after_match", "]", "message", ".", "append_string", "options", "[", ":chunk_separator", "]", "message", ".", "append_ints", "options", "[", ":limit", "]", ",", "options", "[", ":around", "]", "message", ".", "append_array", "options", "[", ":docs", "]", "message", ".", "to_s", "end" ]
Generation of the message to send to Sphinx for an excerpts request.
[ "Generation", "of", "the", "message", "to", "send", "to", "Sphinx", "for", "an", "excerpts", "request", "." ]
4cd51cb37cc2c1000c9c1e873cef5109d291899e
https://github.com/pat/riddle/blob/4cd51cb37cc2c1000c9c1e873cef5109d291899e/lib/riddle/client.rb#L792-L808
train
pat/riddle
lib/riddle/client.rb
Riddle.Client.update_message
def update_message(index, attributes, values_by_doc) message = Message.new message.append_string index message.append_array attributes message.append_int values_by_doc.length values_by_doc.each do |key,values| message.append_64bit_int key # document ID message.append_ints *values # array of new values (integers) end message.to_s end
ruby
def update_message(index, attributes, values_by_doc) message = Message.new message.append_string index message.append_array attributes message.append_int values_by_doc.length values_by_doc.each do |key,values| message.append_64bit_int key # document ID message.append_ints *values # array of new values (integers) end message.to_s end
[ "def", "update_message", "(", "index", ",", "attributes", ",", "values_by_doc", ")", "message", "=", "Message", ".", "new", "message", ".", "append_string", "index", "message", ".", "append_array", "attributes", "message", ".", "append_int", "values_by_doc", ".", "length", "values_by_doc", ".", "each", "do", "|", "key", ",", "values", "|", "message", ".", "append_64bit_int", "key", "message", ".", "append_ints", "*", "values", "end", "message", ".", "to_s", "end" ]
Generation of the message to send to Sphinx to update attributes of a document.
[ "Generation", "of", "the", "message", "to", "send", "to", "Sphinx", "to", "update", "attributes", "of", "a", "document", "." ]
4cd51cb37cc2c1000c9c1e873cef5109d291899e
https://github.com/pat/riddle/blob/4cd51cb37cc2c1000c9c1e873cef5109d291899e/lib/riddle/client.rb#L812-L825
train
pat/riddle
lib/riddle/client.rb
Riddle.Client.keywords_message
def keywords_message(query, index, return_hits) message = Message.new message.append_string query message.append_string index message.append_int return_hits ? 1 : 0 message.to_s end
ruby
def keywords_message(query, index, return_hits) message = Message.new message.append_string query message.append_string index message.append_int return_hits ? 1 : 0 message.to_s end
[ "def", "keywords_message", "(", "query", ",", "index", ",", "return_hits", ")", "message", "=", "Message", ".", "new", "message", ".", "append_string", "query", "message", ".", "append_string", "index", "message", ".", "append_int", "return_hits", "?", "1", ":", "0", "message", ".", "to_s", "end" ]
Generates the simple message to send to the daemon for a keywords request.
[ "Generates", "the", "simple", "message", "to", "send", "to", "the", "daemon", "for", "a", "keywords", "request", "." ]
4cd51cb37cc2c1000c9c1e873cef5109d291899e
https://github.com/pat/riddle/blob/4cd51cb37cc2c1000c9c1e873cef5109d291899e/lib/riddle/client.rb#L828-L836
train
kevindew/openapi3_parser
lib/openapi3_parser/document.rb
Openapi3Parser.Document.errors
def errors reference_factories.inject(factory.errors) do |memo, f| Validation::ErrorCollection.combine(memo, f.errors) end end
ruby
def errors reference_factories.inject(factory.errors) do |memo, f| Validation::ErrorCollection.combine(memo, f.errors) end end
[ "def", "errors", "reference_factories", ".", "inject", "(", "factory", ".", "errors", ")", "do", "|", "memo", ",", "f", "|", "Validation", "::", "ErrorCollection", ".", "combine", "(", "memo", ",", "f", ".", "errors", ")", "end", "end" ]
Any validation errors that are present on the OpenAPI document @return [Validation::ErrorCollection]
[ "Any", "validation", "errors", "that", "are", "present", "on", "the", "OpenAPI", "document" ]
70c599f03bb6c26726bed200907cabf5ceec225d
https://github.com/kevindew/openapi3_parser/blob/70c599f03bb6c26726bed200907cabf5ceec225d/lib/openapi3_parser/document.rb#L115-L119
train
kevindew/openapi3_parser
lib/openapi3_parser/source.rb
Openapi3Parser.Source.register_reference
def register_reference(given_reference, factory, context) reference = Reference.new(given_reference) ReferenceResolver.new( reference, factory, context ).tap do |resolver| next if resolver.in_root_source? reference_register.register(resolver.reference_factory) end end
ruby
def register_reference(given_reference, factory, context) reference = Reference.new(given_reference) ReferenceResolver.new( reference, factory, context ).tap do |resolver| next if resolver.in_root_source? reference_register.register(resolver.reference_factory) end end
[ "def", "register_reference", "(", "given_reference", ",", "factory", ",", "context", ")", "reference", "=", "Reference", ".", "new", "(", "given_reference", ")", "ReferenceResolver", ".", "new", "(", "reference", ",", "factory", ",", "context", ")", ".", "tap", "do", "|", "resolver", "|", "next", "if", "resolver", ".", "in_root_source?", "reference_register", ".", "register", "(", "resolver", ".", "reference_factory", ")", "end", "end" ]
Used to register a reference with the underlying document and return a reference resolver to access the object referenced @param [String] given_reference The reference as text @param [NodeFactory] factory Factory class for the expected eventual resource @param [Context] context The context of the object calling this reference @return [ReferenceResolver]
[ "Used", "to", "register", "a", "reference", "with", "the", "underlying", "document", "and", "return", "a", "reference", "resolver", "to", "access", "the", "object", "referenced" ]
70c599f03bb6c26726bed200907cabf5ceec225d
https://github.com/kevindew/openapi3_parser/blob/70c599f03bb6c26726bed200907cabf5ceec225d/lib/openapi3_parser/source.rb#L55-L63
train
kevindew/openapi3_parser
lib/openapi3_parser/source.rb
Openapi3Parser.Source.data_at_pointer
def data_at_pointer(json_pointer) return data if json_pointer.empty? data.dig(*json_pointer) if data.respond_to?(:dig) end
ruby
def data_at_pointer(json_pointer) return data if json_pointer.empty? data.dig(*json_pointer) if data.respond_to?(:dig) end
[ "def", "data_at_pointer", "(", "json_pointer", ")", "return", "data", "if", "json_pointer", ".", "empty?", "data", ".", "dig", "(", "*", "json_pointer", ")", "if", "data", ".", "respond_to?", "(", ":dig", ")", "end" ]
Access the data in a source at a particular pointer @param [Array] json_pointer An array of segments of a JSON pointer @return [Object]
[ "Access", "the", "data", "in", "a", "source", "at", "a", "particular", "pointer" ]
70c599f03bb6c26726bed200907cabf5ceec225d
https://github.com/kevindew/openapi3_parser/blob/70c599f03bb6c26726bed200907cabf5ceec225d/lib/openapi3_parser/source.rb#L91-L94
train
greyblake/blogo
lib/blogo/paginator.rb
Blogo.Paginator.pages
def pages @pages ||= begin from = @page - (@size / 2).ceil from = 1 if from < 1 upto = from + @size - 1 # Correct +from+ and +to+ if +to+ is more than number of pages if upto > pages_count from -= (upto - pages_count) from = 1 if from < 1 upto = pages_count end (from..upto).to_a end end
ruby
def pages @pages ||= begin from = @page - (@size / 2).ceil from = 1 if from < 1 upto = from + @size - 1 # Correct +from+ and +to+ if +to+ is more than number of pages if upto > pages_count from -= (upto - pages_count) from = 1 if from < 1 upto = pages_count end (from..upto).to_a end end
[ "def", "pages", "@pages", "||=", "begin", "from", "=", "@page", "-", "(", "@size", "/", "2", ")", ".", "ceil", "from", "=", "1", "if", "from", "<", "1", "upto", "=", "from", "+", "@size", "-", "1", "if", "upto", ">", "pages_count", "from", "-=", "(", "upto", "-", "pages_count", ")", "from", "=", "1", "if", "from", "<", "1", "upto", "=", "pages_count", "end", "(", "from", "..", "upto", ")", ".", "to_a", "end", "end" ]
Number of pages to display. @return [Array<Integer>]
[ "Number", "of", "pages", "to", "display", "." ]
eee0a8854cfdc309763197e3ef9b295008be85f6
https://github.com/greyblake/blogo/blob/eee0a8854cfdc309763197e3ef9b295008be85f6/lib/blogo/paginator.rb#L57-L72
train
danger/danger-mention
lib/danger_plugin.rb
Danger.DangerMention.run
def run(max_reviewers = 3, file_blacklist = [], user_blacklist = []) files = select_files(file_blacklist) return if files.empty? authors = {} compose_urls(files).each do |url| result = parse_blame(url) authors.merge!(result) { |_, m, n| m + n } end reviewers = find_reviewers(authors, user_blacklist, max_reviewers) if reviewers.count > 0 reviewers = reviewers.map { |r| '@' + r } result = format('By analyzing the blame information on this pull '\ 'request, we identified %s to be potential reviewer%s.', reviewers.join(', '), reviewers.count > 1 ? 's' : '') markdown result end end
ruby
def run(max_reviewers = 3, file_blacklist = [], user_blacklist = []) files = select_files(file_blacklist) return if files.empty? authors = {} compose_urls(files).each do |url| result = parse_blame(url) authors.merge!(result) { |_, m, n| m + n } end reviewers = find_reviewers(authors, user_blacklist, max_reviewers) if reviewers.count > 0 reviewers = reviewers.map { |r| '@' + r } result = format('By analyzing the blame information on this pull '\ 'request, we identified %s to be potential reviewer%s.', reviewers.join(', '), reviewers.count > 1 ? 's' : '') markdown result end end
[ "def", "run", "(", "max_reviewers", "=", "3", ",", "file_blacklist", "=", "[", "]", ",", "user_blacklist", "=", "[", "]", ")", "files", "=", "select_files", "(", "file_blacklist", ")", "return", "if", "files", ".", "empty?", "authors", "=", "{", "}", "compose_urls", "(", "files", ")", ".", "each", "do", "|", "url", "|", "result", "=", "parse_blame", "(", "url", ")", "authors", ".", "merge!", "(", "result", ")", "{", "|", "_", ",", "m", ",", "n", "|", "m", "+", "n", "}", "end", "reviewers", "=", "find_reviewers", "(", "authors", ",", "user_blacklist", ",", "max_reviewers", ")", "if", "reviewers", ".", "count", ">", "0", "reviewers", "=", "reviewers", ".", "map", "{", "|", "r", "|", "'@'", "+", "r", "}", "result", "=", "format", "(", "'By analyzing the blame information on this pull '", "'request, we identified %s to be potential reviewer%s.'", ",", "reviewers", ".", "join", "(", "', '", ")", ",", "reviewers", ".", "count", ">", "1", "?", "'s'", ":", "''", ")", "markdown", "result", "end", "end" ]
Mention potential reviewers. @param [Integer] max_reviewers Maximum number of people to ping in the PR message, default is 3. @param [Array<String>] file_blacklist Regexes of ignored files. @param [Array<String>] user_blacklist List of users that will never be mentioned. @return [void]
[ "Mention", "potential", "reviewers", "." ]
3b2d07363409b28c2ca707cfde89abccd3ea839a
https://github.com/danger/danger-mention/blob/3b2d07363409b28c2ca707cfde89abccd3ea839a/lib/danger_plugin.rb#L40-L61
train
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.push
def push(node) node = Node(node) @head ||= node if @tail @tail.next = node node.prev = @tail end @tail = node @length += 1 self end
ruby
def push(node) node = Node(node) @head ||= node if @tail @tail.next = node node.prev = @tail end @tail = node @length += 1 self end
[ "def", "push", "(", "node", ")", "node", "=", "Node", "(", "node", ")", "@head", "||=", "node", "if", "@tail", "@tail", ".", "next", "=", "node", "node", ".", "prev", "=", "@tail", "end", "@tail", "=", "node", "@length", "+=", "1", "self", "end" ]
Pushes new nodes to the end of the list. == Parameters: node:: Any object, including +Node+ objects. == Returns: +self+ of +List+ object.
[ "Pushes", "new", "nodes", "to", "the", "end", "of", "the", "list", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L36-L49
train
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.unshift
def unshift(node) node = Node(node) @tail ||= node node.next = @head @head.prev = node if @head @head = node @length += 1 self end
ruby
def unshift(node) node = Node(node) @tail ||= node node.next = @head @head.prev = node if @head @head = node @length += 1 self end
[ "def", "unshift", "(", "node", ")", "node", "=", "Node", "(", "node", ")", "@tail", "||=", "node", "node", ".", "next", "=", "@head", "@head", ".", "prev", "=", "node", "if", "@head", "@head", "=", "node", "@length", "+=", "1", "self", "end" ]
Pushes new nodes on top of the list. == Parameters: node:: Any object, including +Node+ objects. == Returns: +self+ of +List+ object.
[ "Pushes", "new", "nodes", "on", "top", "of", "the", "list", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L60-L70
train
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.insert
def insert(to_add, after: nil, before: nil) if after && before || !after && !before raise ArgumentError, 'either :after or :before keys should be passed' end matcher = after || before matcher_proc = if matcher.is_a?(Proc) __to_matcher(&matcher) else __to_matcher(matcher) end node = each_node.find(&matcher_proc) return unless node new_node = after ? insert_after_node(to_add, node) : insert_before_node(to_add, node) new_node.data end
ruby
def insert(to_add, after: nil, before: nil) if after && before || !after && !before raise ArgumentError, 'either :after or :before keys should be passed' end matcher = after || before matcher_proc = if matcher.is_a?(Proc) __to_matcher(&matcher) else __to_matcher(matcher) end node = each_node.find(&matcher_proc) return unless node new_node = after ? insert_after_node(to_add, node) : insert_before_node(to_add, node) new_node.data end
[ "def", "insert", "(", "to_add", ",", "after", ":", "nil", ",", "before", ":", "nil", ")", "if", "after", "&&", "before", "||", "!", "after", "&&", "!", "before", "raise", "ArgumentError", ",", "'either :after or :before keys should be passed'", "end", "matcher", "=", "after", "||", "before", "matcher_proc", "=", "if", "matcher", ".", "is_a?", "(", "Proc", ")", "__to_matcher", "(", "&", "matcher", ")", "else", "__to_matcher", "(", "matcher", ")", "end", "node", "=", "each_node", ".", "find", "(", "&", "matcher_proc", ")", "return", "unless", "node", "new_node", "=", "after", "?", "insert_after_node", "(", "to_add", ",", "node", ")", ":", "insert_before_node", "(", "to_add", ",", "node", ")", "new_node", ".", "data", "end" ]
Inserts after or before first matched node.data from the the list by passed block or value. == Returns: Inserted node data
[ "Inserts", "after", "or", "before", "first", "matched", "node", ".", "data", "from", "the", "the", "list", "by", "passed", "block", "or", "value", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L77-L91
train
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.insert_after_node
def insert_after_node(data, node) Node(data).tap do |new_node| new_node.prev = node new_node.next = node.next if node.next node.next.prev = new_node else @tail = new_node end node.next = new_node @length += 1 end end
ruby
def insert_after_node(data, node) Node(data).tap do |new_node| new_node.prev = node new_node.next = node.next if node.next node.next.prev = new_node else @tail = new_node end node.next = new_node @length += 1 end end
[ "def", "insert_after_node", "(", "data", ",", "node", ")", "Node", "(", "data", ")", ".", "tap", "do", "|", "new_node", "|", "new_node", ".", "prev", "=", "node", "new_node", ".", "next", "=", "node", ".", "next", "if", "node", ".", "next", "node", ".", "next", ".", "prev", "=", "new_node", "else", "@tail", "=", "new_node", "end", "node", ".", "next", "=", "new_node", "@length", "+=", "1", "end", "end" ]
Inserts data after first matched node.data. == Returns: Inserted node
[ "Inserts", "data", "after", "first", "matched", "node", ".", "data", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L98-L110
train
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.insert_before_node
def insert_before_node(data, node) Node(data).tap do |new_node| new_node.next = node new_node.prev = node.prev if node.prev node.prev.next = new_node else @head = new_node end node.prev = new_node @length += 1 end end
ruby
def insert_before_node(data, node) Node(data).tap do |new_node| new_node.next = node new_node.prev = node.prev if node.prev node.prev.next = new_node else @head = new_node end node.prev = new_node @length += 1 end end
[ "def", "insert_before_node", "(", "data", ",", "node", ")", "Node", "(", "data", ")", ".", "tap", "do", "|", "new_node", "|", "new_node", ".", "next", "=", "node", "new_node", ".", "prev", "=", "node", ".", "prev", "if", "node", ".", "prev", "node", ".", "prev", ".", "next", "=", "new_node", "else", "@head", "=", "new_node", "end", "node", ".", "prev", "=", "new_node", "@length", "+=", "1", "end", "end" ]
Inserts data before first matched node.data. == Returns: Inserted node
[ "Inserts", "data", "before", "first", "matched", "node", ".", "data", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L117-L129
train
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.delete
def delete(val = nil, &block) if val.respond_to?(:to_node) node = val.to_node __unlink_node(node) return node.data end each_node.find(&__to_matcher(val, &block)).tap do |node_to_delete| return unless node_to_delete __unlink_node(node_to_delete) end.data end
ruby
def delete(val = nil, &block) if val.respond_to?(:to_node) node = val.to_node __unlink_node(node) return node.data end each_node.find(&__to_matcher(val, &block)).tap do |node_to_delete| return unless node_to_delete __unlink_node(node_to_delete) end.data end
[ "def", "delete", "(", "val", "=", "nil", ",", "&", "block", ")", "if", "val", ".", "respond_to?", "(", ":to_node", ")", "node", "=", "val", ".", "to_node", "__unlink_node", "(", "node", ")", "return", "node", ".", "data", "end", "each_node", ".", "find", "(", "&", "__to_matcher", "(", "val", ",", "&", "block", ")", ")", ".", "tap", "do", "|", "node_to_delete", "|", "return", "unless", "node_to_delete", "__unlink_node", "(", "node_to_delete", ")", "end", ".", "data", "end" ]
Removes first matched node.data from the the list by passed block or value. If +val+ is a +Node+, removes that node from the list. Behavior is undefined if +val+ is a +Node+ that's not a member of this list. == Returns: Deleted node's data
[ "Removes", "first", "matched", "node", ".", "data", "from", "the", "the", "list", "by", "passed", "block", "or", "value", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L139-L150
train
spectator/linked-list
lib/linked-list/list.rb
LinkedList.List.delete_all
def delete_all(val = nil, &block) each_node.select(&__to_matcher(val, &block)).each do |node_to_delete| next unless node_to_delete __unlink_node(node_to_delete) end.map(&:data) end
ruby
def delete_all(val = nil, &block) each_node.select(&__to_matcher(val, &block)).each do |node_to_delete| next unless node_to_delete __unlink_node(node_to_delete) end.map(&:data) end
[ "def", "delete_all", "(", "val", "=", "nil", ",", "&", "block", ")", "each_node", ".", "select", "(", "&", "__to_matcher", "(", "val", ",", "&", "block", ")", ")", ".", "each", "do", "|", "node_to_delete", "|", "next", "unless", "node_to_delete", "__unlink_node", "(", "node_to_delete", ")", "end", ".", "map", "(", "&", ":data", ")", "end" ]
Removes all matched data.data from the the list by passed block or value. == Returns: Array of deleted nodes
[ "Removes", "all", "matched", "data", ".", "data", "from", "the", "the", "list", "by", "passed", "block", "or", "value", "." ]
f4e0d62fbc129282374f91d4fbcc699f7c330bd4
https://github.com/spectator/linked-list/blob/f4e0d62fbc129282374f91d4fbcc699f7c330bd4/lib/linked-list/list.rb#L157-L162
train
wycats/merb
merb-core/lib/merb-core/dispatch/session/store_container.rb
Merb.SessionStoreContainer.regenerate
def regenerate store.delete_session(self.session_id) self.session_id = Merb::SessionMixin.rand_uuid store.store_session(self.session_id, self) end
ruby
def regenerate store.delete_session(self.session_id) self.session_id = Merb::SessionMixin.rand_uuid store.store_session(self.session_id, self) end
[ "def", "regenerate", "store", ".", "delete_session", "(", "self", ".", "session_id", ")", "self", ".", "session_id", "=", "Merb", "::", "SessionMixin", ".", "rand_uuid", "store", ".", "store_session", "(", "self", ".", "session_id", ",", "self", ")", "end" ]
Regenerate the session ID. :api: private
[ "Regenerate", "the", "session", "ID", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/store_container.rb#L156-L160
train
wycats/merb
merb-gen/lib/generators/templates/application/merb_core/doc/rdoc/generators/merb_generator.rb
Generators.ContextUser.collect_methods
def collect_methods list = @context.method_list unless @options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end @methods = list.collect {|m| HtmlMethod.new(m, self, @options) } end
ruby
def collect_methods list = @context.method_list unless @options.show_all list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation } end @methods = list.collect {|m| HtmlMethod.new(m, self, @options) } end
[ "def", "collect_methods", "list", "=", "@context", ".", "method_list", "unless", "@options", ".", "show_all", "list", "=", "list", ".", "find_all", "{", "|", "m", "|", "m", ".", "visibility", "==", ":public", "||", "m", ".", "visibility", "==", ":protected", "||", "m", ".", "force_documentation", "}", "end", "@methods", "=", "list", ".", "collect", "{", "|", "m", "|", "HtmlMethod", ".", "new", "(", "m", ",", "self", ",", "@options", ")", "}", "end" ]
Create a list of HtmlMethod objects for each method in the corresponding context object. If the @options.show_all variable is set (corresponding to the <tt>--all</tt> option, we include all methods, otherwise just the public ones.
[ "Create", "a", "list", "of", "HtmlMethod", "objects", "for", "each", "method", "in", "the", "corresponding", "context", "object", ".", "If", "the" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-gen/lib/generators/templates/application/merb_core/doc/rdoc/generators/merb_generator.rb#L286-L292
train
wycats/merb
merb-gen/lib/generators/templates/application/merb_core/doc/rdoc/generators/merb_generator.rb
Generators.HtmlMethod.markup_code
def markup_code(tokens) src = "" tokens.each do |t| next unless t # p t.class # style = STYLE_MAP[t.class] style = case t when RubyToken::TkCONSTANT then "ruby-constant" when RubyToken::TkKW then "ruby-keyword kw" when RubyToken::TkIVAR then "ruby-ivar" when RubyToken::TkOp then "ruby-operator" when RubyToken::TkId then "ruby-identifier" when RubyToken::TkNode then "ruby-node" when RubyToken::TkCOMMENT then "ruby-comment cmt" when RubyToken::TkREGEXP then "ruby-regexp re" when RubyToken::TkSTRING then "ruby-value str" when RubyToken::TkVal then "ruby-value" else nil end text = CGI.escapeHTML(t.text) if style src << "<span class=\"#{style}\">#{text}</span>" else src << text end end add_line_numbers(src) src end
ruby
def markup_code(tokens) src = "" tokens.each do |t| next unless t # p t.class # style = STYLE_MAP[t.class] style = case t when RubyToken::TkCONSTANT then "ruby-constant" when RubyToken::TkKW then "ruby-keyword kw" when RubyToken::TkIVAR then "ruby-ivar" when RubyToken::TkOp then "ruby-operator" when RubyToken::TkId then "ruby-identifier" when RubyToken::TkNode then "ruby-node" when RubyToken::TkCOMMENT then "ruby-comment cmt" when RubyToken::TkREGEXP then "ruby-regexp re" when RubyToken::TkSTRING then "ruby-value str" when RubyToken::TkVal then "ruby-value" else nil end text = CGI.escapeHTML(t.text) if style src << "<span class=\"#{style}\">#{text}</span>" else src << text end end add_line_numbers(src) src end
[ "def", "markup_code", "(", "tokens", ")", "src", "=", "\"\"", "tokens", ".", "each", "do", "|", "t", "|", "next", "unless", "t", "style", "=", "case", "t", "when", "RubyToken", "::", "TkCONSTANT", "then", "\"ruby-constant\"", "when", "RubyToken", "::", "TkKW", "then", "\"ruby-keyword kw\"", "when", "RubyToken", "::", "TkIVAR", "then", "\"ruby-ivar\"", "when", "RubyToken", "::", "TkOp", "then", "\"ruby-operator\"", "when", "RubyToken", "::", "TkId", "then", "\"ruby-identifier\"", "when", "RubyToken", "::", "TkNode", "then", "\"ruby-node\"", "when", "RubyToken", "::", "TkCOMMENT", "then", "\"ruby-comment cmt\"", "when", "RubyToken", "::", "TkREGEXP", "then", "\"ruby-regexp re\"", "when", "RubyToken", "::", "TkSTRING", "then", "\"ruby-value str\"", "when", "RubyToken", "::", "TkVal", "then", "\"ruby-value\"", "else", "nil", "end", "text", "=", "CGI", ".", "escapeHTML", "(", "t", ".", "text", ")", "if", "style", "src", "<<", "\"<span class=\\\"#{style}\\\">#{text}</span>\"", "else", "src", "<<", "text", "end", "end", "add_line_numbers", "(", "src", ")", "src", "end" ]
Given a sequence of source tokens, mark up the source code to make it look purty.
[ "Given", "a", "sequence", "of", "source", "tokens", "mark", "up", "the", "source", "code", "to", "make", "it", "look", "purty", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-gen/lib/generators/templates/application/merb_core/doc/rdoc/generators/merb_generator.rb#L1056-L1088
train
wycats/merb
merb-mailer/lib/merb-mailer/mailer.rb
Merb.Mailer.net_smtp
def net_smtp smtp = Net::SMTP.new(config[:host], config[:port].to_i) if config[:tls] if smtp.respond_to?(:enable_starttls) # 1.9.x smtp.enable_starttls elsif smtp.respond_to?(:enable_tls) && smtp.respond_to?(:use_tls?) smtp.enable_tls(OpenSSL::SSL::VERIFY_NONE) # 1.8.x with tlsmail else raise 'Unable to enable TLS, for Ruby 1.8.x install tlsmail' end end smtp.start(config[:domain], config[:user], config[:pass], config[:auth]) { |smtp| to = @mail.to.is_a?(String) ? @mail.to.split(/[,;]/) : @mail.to smtp.send_message(@mail.to_s, @mail.from.first, to) } end
ruby
def net_smtp smtp = Net::SMTP.new(config[:host], config[:port].to_i) if config[:tls] if smtp.respond_to?(:enable_starttls) # 1.9.x smtp.enable_starttls elsif smtp.respond_to?(:enable_tls) && smtp.respond_to?(:use_tls?) smtp.enable_tls(OpenSSL::SSL::VERIFY_NONE) # 1.8.x with tlsmail else raise 'Unable to enable TLS, for Ruby 1.8.x install tlsmail' end end smtp.start(config[:domain], config[:user], config[:pass], config[:auth]) { |smtp| to = @mail.to.is_a?(String) ? @mail.to.split(/[,;]/) : @mail.to smtp.send_message(@mail.to_s, @mail.from.first, to) } end
[ "def", "net_smtp", "smtp", "=", "Net", "::", "SMTP", ".", "new", "(", "config", "[", ":host", "]", ",", "config", "[", ":port", "]", ".", "to_i", ")", "if", "config", "[", ":tls", "]", "if", "smtp", ".", "respond_to?", "(", ":enable_starttls", ")", "smtp", ".", "enable_starttls", "elsif", "smtp", ".", "respond_to?", "(", ":enable_tls", ")", "&&", "smtp", ".", "respond_to?", "(", ":use_tls?", ")", "smtp", ".", "enable_tls", "(", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", ")", "else", "raise", "'Unable to enable TLS, for Ruby 1.8.x install tlsmail'", "end", "end", "smtp", ".", "start", "(", "config", "[", ":domain", "]", ",", "config", "[", ":user", "]", ",", "config", "[", ":pass", "]", ",", "config", "[", ":auth", "]", ")", "{", "|", "smtp", "|", "to", "=", "@mail", ".", "to", ".", "is_a?", "(", "String", ")", "?", "@mail", ".", "to", ".", "split", "(", "/", "/", ")", ":", "@mail", ".", "to", "smtp", ".", "send_message", "(", "@mail", ".", "to_s", ",", "@mail", ".", "from", ".", "first", ",", "to", ")", "}", "end" ]
Sends the mail using SMTP.
[ "Sends", "the", "mail", "using", "SMTP", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-mailer/lib/merb-mailer/mailer.rb#L57-L72
train
wycats/merb
merb-core/lib/merb-core/dispatch/worker.rb
Merb.Worker.process_queue
def process_queue begin while blk = Merb::Dispatcher.work_queue.pop # we've been blocking on the queue waiting for an item sleeping. # when someone pushes an item it wakes up this thread so we # immediately pass execution to the scheduler so we don't # accidentally run this block before the action finishes # it's own processing Thread.pass blk.call break if Merb::Dispatcher.work_queue.empty? && Merb.exiting end rescue Exception => e Merb.logger.warn! %Q!Worker Thread Crashed with Exception:\n#{Merb.exception(e)}\nRestarting Worker Thread! retry end end
ruby
def process_queue begin while blk = Merb::Dispatcher.work_queue.pop # we've been blocking on the queue waiting for an item sleeping. # when someone pushes an item it wakes up this thread so we # immediately pass execution to the scheduler so we don't # accidentally run this block before the action finishes # it's own processing Thread.pass blk.call break if Merb::Dispatcher.work_queue.empty? && Merb.exiting end rescue Exception => e Merb.logger.warn! %Q!Worker Thread Crashed with Exception:\n#{Merb.exception(e)}\nRestarting Worker Thread! retry end end
[ "def", "process_queue", "begin", "while", "blk", "=", "Merb", "::", "Dispatcher", ".", "work_queue", ".", "pop", "Thread", ".", "pass", "blk", ".", "call", "break", "if", "Merb", "::", "Dispatcher", ".", "work_queue", ".", "empty?", "&&", "Merb", ".", "exiting", "end", "rescue", "Exception", "=>", "e", "Merb", ".", "logger", ".", "warn!", "%Q!Worker Thread Crashed with Exception:\\n#{Merb.exception(e)}\\nRestarting Worker Thread!", "retry", "end", "end" ]
Creates a new worker thread that loops over the work queue. :api: private Processes tasks in the Merb::Dispatcher.work_queue. :api: private
[ "Creates", "a", "new", "worker", "thread", "that", "loops", "over", "the", "work", "queue", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/worker.rb#L49-L65
train
wycats/merb
merb-core/lib/merb-core/dispatch/dispatcher.rb
Merb.Request.handle
def handle @start = env["merb.request_start"] = Time.now Merb.logger.info { "Started request handling: #{start.to_s}" } find_route! return rack_response if handled? klass = controller Merb.logger.debug { "Routed to: #{klass::_filter_params(params).inspect}" } unless klass < Controller raise NotFound, "Controller '#{klass}' not found.\n" \ "If Merb tries to find a controller for static files, " \ "you may need to check your Rackup file, see the Problems " \ "section at: http://wiki.merbivore.com/pages/rack-middleware" end if klass.abstract? raise NotFound, "The '#{klass}' controller has no public actions" end dispatch_action(klass, params[:action]) rescue Object => exception dispatch_exception(exception) end
ruby
def handle @start = env["merb.request_start"] = Time.now Merb.logger.info { "Started request handling: #{start.to_s}" } find_route! return rack_response if handled? klass = controller Merb.logger.debug { "Routed to: #{klass::_filter_params(params).inspect}" } unless klass < Controller raise NotFound, "Controller '#{klass}' not found.\n" \ "If Merb tries to find a controller for static files, " \ "you may need to check your Rackup file, see the Problems " \ "section at: http://wiki.merbivore.com/pages/rack-middleware" end if klass.abstract? raise NotFound, "The '#{klass}' controller has no public actions" end dispatch_action(klass, params[:action]) rescue Object => exception dispatch_exception(exception) end
[ "def", "handle", "@start", "=", "env", "[", "\"merb.request_start\"", "]", "=", "Time", ".", "now", "Merb", ".", "logger", ".", "info", "{", "\"Started request handling: #{start.to_s}\"", "}", "find_route!", "return", "rack_response", "if", "handled?", "klass", "=", "controller", "Merb", ".", "logger", ".", "debug", "{", "\"Routed to: #{klass::_filter_params(params).inspect}\"", "}", "unless", "klass", "<", "Controller", "raise", "NotFound", ",", "\"Controller '#{klass}' not found.\\n\"", "\"If Merb tries to find a controller for static files, \"", "\"you may need to check your Rackup file, see the Problems \"", "\"section at: http://wiki.merbivore.com/pages/rack-middleware\"", "end", "if", "klass", ".", "abstract?", "raise", "NotFound", ",", "\"The '#{klass}' controller has no public actions\"", "end", "dispatch_action", "(", "klass", ",", "params", "[", ":action", "]", ")", "rescue", "Object", "=>", "exception", "dispatch_exception", "(", "exception", ")", "end" ]
Handles request routing and action dispatch. ==== Returns Array[Integer, Hash, #each]:: A Rack response :api: private
[ "Handles", "request", "routing", "and", "action", "dispatch", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/dispatcher.rb#L54-L79
train
wycats/merb
merb-core/lib/merb-core/dispatch/dispatcher.rb
Merb.Request.dispatch_action
def dispatch_action(klass, action_name, status=200) @env["merb.status"] = status @env["merb.action_name"] = action_name if Dispatcher.use_mutex @@mutex.synchronize { klass.call(env) } else klass.call(env) end end
ruby
def dispatch_action(klass, action_name, status=200) @env["merb.status"] = status @env["merb.action_name"] = action_name if Dispatcher.use_mutex @@mutex.synchronize { klass.call(env) } else klass.call(env) end end
[ "def", "dispatch_action", "(", "klass", ",", "action_name", ",", "status", "=", "200", ")", "@env", "[", "\"merb.status\"", "]", "=", "status", "@env", "[", "\"merb.action_name\"", "]", "=", "action_name", "if", "Dispatcher", ".", "use_mutex", "@@mutex", ".", "synchronize", "{", "klass", ".", "call", "(", "env", ")", "}", "else", "klass", ".", "call", "(", "env", ")", "end", "end" ]
Setup the controller and call the chosen action ==== Parameters klass<Merb::Controller>:: The controller class to dispatch to. action<Symbol>:: The action to dispatch. status<Integer>:: The status code to respond with. ==== Returns Array[Integer, Hash, #each]:: A Rack response :api: private
[ "Setup", "the", "controller", "and", "call", "the", "chosen", "action" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/dispatcher.rb#L93-L102
train
wycats/merb
merb-core/lib/merb-core/dispatch/dispatcher.rb
Merb.Request.dispatch_exception
def dispatch_exception(exception) if(exception.is_a?(Merb::ControllerExceptions::Base) && !exception.is_a?(Merb::ControllerExceptions::ServerError)) Merb.logger.info(Merb.exception(exception)) else Merb.logger.error(Merb.exception(exception)) end exceptions = env["merb.exceptions"] = [exception] begin e = exceptions.first if action_name = e.action_name dispatch_action(Exceptions, action_name, e.class.status) else dispatch_action(Dispatcher::DefaultException, :index, e.class.status) end rescue Object => dispatch_issue if e.same?(dispatch_issue) || exceptions.size > 5 dispatch_action(Dispatcher::DefaultException, :index, e.class.status) else Merb.logger.error("Dispatching #{e.class} raised another error.") Merb.logger.error(Merb.exception(dispatch_issue)) exceptions.unshift dispatch_issue retry end end end
ruby
def dispatch_exception(exception) if(exception.is_a?(Merb::ControllerExceptions::Base) && !exception.is_a?(Merb::ControllerExceptions::ServerError)) Merb.logger.info(Merb.exception(exception)) else Merb.logger.error(Merb.exception(exception)) end exceptions = env["merb.exceptions"] = [exception] begin e = exceptions.first if action_name = e.action_name dispatch_action(Exceptions, action_name, e.class.status) else dispatch_action(Dispatcher::DefaultException, :index, e.class.status) end rescue Object => dispatch_issue if e.same?(dispatch_issue) || exceptions.size > 5 dispatch_action(Dispatcher::DefaultException, :index, e.class.status) else Merb.logger.error("Dispatching #{e.class} raised another error.") Merb.logger.error(Merb.exception(dispatch_issue)) exceptions.unshift dispatch_issue retry end end end
[ "def", "dispatch_exception", "(", "exception", ")", "if", "(", "exception", ".", "is_a?", "(", "Merb", "::", "ControllerExceptions", "::", "Base", ")", "&&", "!", "exception", ".", "is_a?", "(", "Merb", "::", "ControllerExceptions", "::", "ServerError", ")", ")", "Merb", ".", "logger", ".", "info", "(", "Merb", ".", "exception", "(", "exception", ")", ")", "else", "Merb", ".", "logger", ".", "error", "(", "Merb", ".", "exception", "(", "exception", ")", ")", "end", "exceptions", "=", "env", "[", "\"merb.exceptions\"", "]", "=", "[", "exception", "]", "begin", "e", "=", "exceptions", ".", "first", "if", "action_name", "=", "e", ".", "action_name", "dispatch_action", "(", "Exceptions", ",", "action_name", ",", "e", ".", "class", ".", "status", ")", "else", "dispatch_action", "(", "Dispatcher", "::", "DefaultException", ",", ":index", ",", "e", ".", "class", ".", "status", ")", "end", "rescue", "Object", "=>", "dispatch_issue", "if", "e", ".", "same?", "(", "dispatch_issue", ")", "||", "exceptions", ".", "size", ">", "5", "dispatch_action", "(", "Dispatcher", "::", "DefaultException", ",", ":index", ",", "e", ".", "class", ".", "status", ")", "else", "Merb", ".", "logger", ".", "error", "(", "\"Dispatching #{e.class} raised another error.\"", ")", "Merb", ".", "logger", ".", "error", "(", "Merb", ".", "exception", "(", "dispatch_issue", ")", ")", "exceptions", ".", "unshift", "dispatch_issue", "retry", "end", "end", "end" ]
Re-route the current request to the Exception controller if it is available, and try to render the exception nicely. You can handle exceptions by implementing actions for specific exceptions such as not_found or for entire classes of exceptions such as client_error. You can also implement handlers for exceptions outside the Merb exception hierarchy (e.g. StandardError is caught in standard_error). ==== Parameters exception<Object>:: The exception object that was created when trying to dispatch the original controller. ==== Returns Array[Integer, Hash, #each]:: A Rack response :api: private
[ "Re", "-", "route", "the", "current", "request", "to", "the", "Exception", "controller", "if", "it", "is", "available", "and", "try", "to", "render", "the", "exception", "nicely", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/dispatcher.rb#L122-L151
train
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.render_chunked
def render_chunked(&blk) must_support_streaming! headers['Transfer-Encoding'] = 'chunked' Proc.new { |response| @response = response response.send_status_no_connection_close('') response.send_header blk.call response.write("0\r\n\r\n") } end
ruby
def render_chunked(&blk) must_support_streaming! headers['Transfer-Encoding'] = 'chunked' Proc.new { |response| @response = response response.send_status_no_connection_close('') response.send_header blk.call response.write("0\r\n\r\n") } end
[ "def", "render_chunked", "(", "&", "blk", ")", "must_support_streaming!", "headers", "[", "'Transfer-Encoding'", "]", "=", "'chunked'", "Proc", ".", "new", "{", "|", "response", "|", "@response", "=", "response", "response", ".", "send_status_no_connection_close", "(", "''", ")", "response", ".", "send_header", "blk", ".", "call", "response", ".", "write", "(", "\"0\\r\\n\\r\\n\"", ")", "}", "end" ]
Renders the block given as a parameter using chunked encoding. ==== Parameters &blk:: A block that, when called, will use send_chunks to send chunks of data down to the server. The chunking will terminate once the block returns. ==== Examples def stream prefix = '<p>' suffix = "</p>\r\n" render_chunked do IO.popen("cat /tmp/test.log") do |io| done = false until done sleep 0.3 line = io.gets.chomp if line == 'EOF' done = true else send_chunk(prefix + line + suffix) end end end end end :api: public
[ "Renders", "the", "block", "given", "as", "a", "parameter", "using", "chunked", "encoding", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L50-L60
train
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.render_then_call
def render_then_call(str, &blk) Proc.new do |response| response.write(str) blk.call end end
ruby
def render_then_call(str, &blk) Proc.new do |response| response.write(str) blk.call end end
[ "def", "render_then_call", "(", "str", ",", "&", "blk", ")", "Proc", ".", "new", "do", "|", "response", "|", "response", ".", "write", "(", "str", ")", "blk", ".", "call", "end", "end" ]
Renders the passed in string, then calls the block outside the mutex and after the string has been returned to the client. ==== Parameters str<String>:: A +String+ to return to the client. &blk:: A block that should get called once the string has been returned. ==== Returns Proc:: A block that Mongrel can call after returning the string to the user. :api: public
[ "Renders", "the", "passed", "in", "string", "then", "calls", "the", "block", "outside", "the", "mutex", "and", "after", "the", "string", "has", "been", "returned", "to", "the", "client", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L104-L109
train
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.send_file
def send_file(file, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename] ? opts[:filename] : File.basename(file)}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) Proc.new do |response| file = File.open(file, 'rb') while chunk = file.read(16384) response.write chunk end file.close end end
ruby
def send_file(file, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename] ? opts[:filename] : File.basename(file)}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) Proc.new do |response| file = File.open(file, 'rb') while chunk = file.read(16384) response.write chunk end file.close end end
[ "def", "send_file", "(", "file", ",", "opts", "=", "{", "}", ")", "opts", ".", "update", "(", "Merb", "::", "Const", "::", "DEFAULT_SEND_FILE_OPTIONS", ".", "merge", "(", "opts", ")", ")", "disposition", "=", "opts", "[", ":disposition", "]", ".", "dup", "||", "'attachment'", "disposition", "<<", "%(; filename=\"#{opts[:filename] ? opts[:filename] : File.basename(file)}\")", "headers", ".", "update", "(", "'Content-Type'", "=>", "opts", "[", ":type", "]", ".", "strip", ",", "'Content-Disposition'", "=>", "disposition", ",", "'Content-Transfer-Encoding'", "=>", "'binary'", ")", "Proc", ".", "new", "do", "|", "response", "|", "file", "=", "File", ".", "open", "(", "file", ",", "'rb'", ")", "while", "chunk", "=", "file", ".", "read", "(", "16384", ")", "response", ".", "write", "chunk", "end", "file", ".", "close", "end", "end" ]
Sends a file over HTTP. When given a path to a file, it will set the right headers so that the static file is served directly. ==== Parameters file<String>:: Path to file to send to the client. opts<Hash>:: Options for sending the file (see below). ==== Options (opts) :disposition<String>:: The disposition of the file send. Defaults to "attachment". :filename<String>:: The name to use for the file. Defaults to the filename of file. :type<String>:: The content type. ==== Returns IO:: An I/O stream for the file. :api: public
[ "Sends", "a", "file", "over", "HTTP", ".", "When", "given", "a", "path", "to", "a", "file", "it", "will", "set", "the", "right", "headers", "so", "that", "the", "static", "file", "is", "served", "directly", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L175-L191
train
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.send_data
def send_data(data, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") if opts[:filename] headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) data end
ruby
def send_data(data, opts={}) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") if opts[:filename] headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary' ) data end
[ "def", "send_data", "(", "data", ",", "opts", "=", "{", "}", ")", "opts", ".", "update", "(", "Merb", "::", "Const", "::", "DEFAULT_SEND_FILE_OPTIONS", ".", "merge", "(", "opts", ")", ")", "disposition", "=", "opts", "[", ":disposition", "]", ".", "dup", "||", "'attachment'", "disposition", "<<", "%(; filename=\"#{opts[:filename]}\")", "if", "opts", "[", ":filename", "]", "headers", ".", "update", "(", "'Content-Type'", "=>", "opts", "[", ":type", "]", ".", "strip", ",", "'Content-Disposition'", "=>", "disposition", ",", "'Content-Transfer-Encoding'", "=>", "'binary'", ")", "data", "end" ]
Send binary data over HTTP to the user as a file download. May set content type, apparent file name, and specify whether to show data inline or download as an attachment. ==== Parameters data<String>:: Path to file to send to the client. opts<Hash>:: Options for sending the data (see below). ==== Options (opts) :disposition<String>:: The disposition of the file send. Defaults to "attachment". :filename<String>:: The name to use for the file. Defaults to the filename of file. :type<String>:: The content type. :api: public
[ "Send", "binary", "data", "over", "HTTP", "to", "the", "user", "as", "a", "file", "download", ".", "May", "set", "content", "type", "apparent", "file", "name", "and", "specify", "whether", "to", "show", "data", "inline", "or", "download", "as", "an", "attachment", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L208-L218
train
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.stream_file
def stream_file(opts={}, &stream) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary', # Rack specification requires header values to respond to :each 'CONTENT-LENGTH' => opts[:content_length].to_s ) Proc.new do |response| stream.call(response) end end
ruby
def stream_file(opts={}, &stream) opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts)) disposition = opts[:disposition].dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") headers.update( 'Content-Type' => opts[:type].strip, # fixes a problem with extra '\r' with some browsers 'Content-Disposition' => disposition, 'Content-Transfer-Encoding' => 'binary', # Rack specification requires header values to respond to :each 'CONTENT-LENGTH' => opts[:content_length].to_s ) Proc.new do |response| stream.call(response) end end
[ "def", "stream_file", "(", "opts", "=", "{", "}", ",", "&", "stream", ")", "opts", ".", "update", "(", "Merb", "::", "Const", "::", "DEFAULT_SEND_FILE_OPTIONS", ".", "merge", "(", "opts", ")", ")", "disposition", "=", "opts", "[", ":disposition", "]", ".", "dup", "||", "'attachment'", "disposition", "<<", "%(; filename=\"#{opts[:filename]}\")", "headers", ".", "update", "(", "'Content-Type'", "=>", "opts", "[", ":type", "]", ".", "strip", ",", "'Content-Disposition'", "=>", "disposition", ",", "'Content-Transfer-Encoding'", "=>", "'binary'", ",", "'CONTENT-LENGTH'", "=>", "opts", "[", ":content_length", "]", ".", "to_s", ")", "Proc", ".", "new", "do", "|", "response", "|", "stream", ".", "call", "(", "response", ")", "end", "end" ]
Streams a file over HTTP. ==== Parameters opts<Hash>:: Options for the file streaming (see below). &stream:: A block that, when called, will return an object that responds to +get_lines+ for streaming. ==== Options :disposition<String>:: The disposition of the file send. Defaults to "attachment". :type<String>:: The content type. :content_length<Numeric>:: The length of the content to send. :filename<String>:: The name to use for the streamed file. ==== Examples stream_file({ :filename => file_name, :type => content_type, :content_length => content_length }) do |response| AWS::S3::S3Object.stream(user.folder_name + "-" + user_file.unique_id, bucket_name) do |chunk| response.write chunk end end :api: public
[ "Streams", "a", "file", "over", "HTTP", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L244-L258
train
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.set_cookie
def set_cookie(name, value, expires) options = expires.is_a?(Hash) ? expires : {:expires => expires} cookies.set_cookie(name, value, options) end
ruby
def set_cookie(name, value, expires) options = expires.is_a?(Hash) ? expires : {:expires => expires} cookies.set_cookie(name, value, options) end
[ "def", "set_cookie", "(", "name", ",", "value", ",", "expires", ")", "options", "=", "expires", ".", "is_a?", "(", "Hash", ")", "?", "expires", ":", "{", ":expires", "=>", "expires", "}", "cookies", ".", "set_cookie", "(", "name", ",", "value", ",", "options", ")", "end" ]
Sets a cookie to be included in the response. If you need to set a cookie, then use the +cookies+ hash. ==== Parameters name<~to_s>:: A name for the cookie. value<~to_s>:: A value for the cookie. expires<~gmtime:~strftime, Hash>:: An expiration time for the cookie, or a hash of cookie options. :api: public
[ "Sets", "a", "cookie", "to", "be", "included", "in", "the", "response", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L306-L309
train
wycats/merb
merb-core/lib/merb-core/controller/mixins/controller.rb
Merb.ControllerMixin.handle_redirect_messages
def handle_redirect_messages(url, opts={}) opts = opts.dup # check opts for message shortcut keys (and assign them to message) [:notice, :error, :success].each do |message_key| if opts[message_key] opts[:message] ||= {} opts[:message][message_key] = opts[message_key] end end # append message query param if message is passed if opts[:message] notice = Merb::Parse.escape([Marshal.dump(opts[:message])].pack("m")) u = ::URI.parse(url) u.query = u.query ? "#{u.query}&_message=#{notice}" : "_message=#{notice}" url = u.to_s end url end
ruby
def handle_redirect_messages(url, opts={}) opts = opts.dup # check opts for message shortcut keys (and assign them to message) [:notice, :error, :success].each do |message_key| if opts[message_key] opts[:message] ||= {} opts[:message][message_key] = opts[message_key] end end # append message query param if message is passed if opts[:message] notice = Merb::Parse.escape([Marshal.dump(opts[:message])].pack("m")) u = ::URI.parse(url) u.query = u.query ? "#{u.query}&_message=#{notice}" : "_message=#{notice}" url = u.to_s end url end
[ "def", "handle_redirect_messages", "(", "url", ",", "opts", "=", "{", "}", ")", "opts", "=", "opts", ".", "dup", "[", ":notice", ",", ":error", ",", ":success", "]", ".", "each", "do", "|", "message_key", "|", "if", "opts", "[", "message_key", "]", "opts", "[", ":message", "]", "||=", "{", "}", "opts", "[", ":message", "]", "[", "message_key", "]", "=", "opts", "[", "message_key", "]", "end", "end", "if", "opts", "[", ":message", "]", "notice", "=", "Merb", "::", "Parse", ".", "escape", "(", "[", "Marshal", ".", "dump", "(", "opts", "[", ":message", "]", ")", "]", ".", "pack", "(", "\"m\"", ")", ")", "u", "=", "::", "URI", ".", "parse", "(", "url", ")", "u", ".", "query", "=", "u", ".", "query", "?", "\"#{u.query}&_message=#{notice}\"", ":", "\"_message=#{notice}\"", "url", "=", "u", ".", "to_s", "end", "url", "end" ]
Process a redirect url with options, appending messages onto the url as query params ==== Parameter url<String>:: the url being redirected to ==== Options (opts) :message<Hash>:: A hash of key/value strings to be passed along within the redirect query params. :notice<String>:: A shortcut to passing :message => {:notice => "..."} :error<String>:: A shortcut to passing :message => {:error => "..."} :success<String>:: A shortcut to passing :message => {:success => "..."} ==== Returns String:: the new url with messages attached :api: private
[ "Process", "a", "redirect", "url", "with", "options", "appending", "messages", "onto", "the", "url", "as", "query", "params" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/controller.rb#L372-L392
train
wycats/merb
merb-core/lib/merb-core/controller/abstract_controller.rb
Merb.AbstractController._call_filters
def _call_filters(filter_set) (filter_set || []).each do |filter, rule| if _call_filter_for_action?(rule, action_name) && _filter_condition_met?(rule) case filter when Symbol, String if rule.key?(:with) args = rule[:with] send(filter, *args) else send(filter) end when Proc then self.instance_eval(&filter) end end end return :filter_chain_completed end
ruby
def _call_filters(filter_set) (filter_set || []).each do |filter, rule| if _call_filter_for_action?(rule, action_name) && _filter_condition_met?(rule) case filter when Symbol, String if rule.key?(:with) args = rule[:with] send(filter, *args) else send(filter) end when Proc then self.instance_eval(&filter) end end end return :filter_chain_completed end
[ "def", "_call_filters", "(", "filter_set", ")", "(", "filter_set", "||", "[", "]", ")", ".", "each", "do", "|", "filter", ",", "rule", "|", "if", "_call_filter_for_action?", "(", "rule", ",", "action_name", ")", "&&", "_filter_condition_met?", "(", "rule", ")", "case", "filter", "when", "Symbol", ",", "String", "if", "rule", ".", "key?", "(", ":with", ")", "args", "=", "rule", "[", ":with", "]", "send", "(", "filter", ",", "*", "args", ")", "else", "send", "(", "filter", ")", "end", "when", "Proc", "then", "self", ".", "instance_eval", "(", "&", "filter", ")", "end", "end", "end", "return", ":filter_chain_completed", "end" ]
Calls a filter chain. ==== Parameters filter_set<Array[Filter]>:: A set of filters in the form [[:filter, rule], [:filter, rule]] ==== Returns Symbol:: :filter_chain_completed. ==== Notes Filter rules can be Symbols, Strings, or Procs. Symbols or Strings:: Call the method represented by the +Symbol+ or +String+. Procs:: Execute the +Proc+, in the context of the controller (self will be the controller) :api: private
[ "Calls", "a", "filter", "chain", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/abstract_controller.rb#L343-L359
train
wycats/merb
merb-core/lib/merb-core/controller/abstract_controller.rb
Merb.AbstractController.absolute_url
def absolute_url(*args) # FIXME: arrgh, why request.protocol returns http://? # :// is not part of protocol name options = extract_options_from_args!(args) || {} protocol = options.delete(:protocol) host = options.delete(:host) raise ArgumentError, "The :protocol option must be specified" unless protocol raise ArgumentError, "The :host option must be specified" unless host args << options protocol + "://" + host + url(*args) end
ruby
def absolute_url(*args) # FIXME: arrgh, why request.protocol returns http://? # :// is not part of protocol name options = extract_options_from_args!(args) || {} protocol = options.delete(:protocol) host = options.delete(:host) raise ArgumentError, "The :protocol option must be specified" unless protocol raise ArgumentError, "The :host option must be specified" unless host args << options protocol + "://" + host + url(*args) end
[ "def", "absolute_url", "(", "*", "args", ")", "options", "=", "extract_options_from_args!", "(", "args", ")", "||", "{", "}", "protocol", "=", "options", ".", "delete", "(", ":protocol", ")", "host", "=", "options", ".", "delete", "(", ":host", ")", "raise", "ArgumentError", ",", "\"The :protocol option must be specified\"", "unless", "protocol", "raise", "ArgumentError", ",", "\"The :host option must be specified\"", "unless", "host", "args", "<<", "options", "protocol", "+", "\"://\"", "+", "host", "+", "url", "(", "*", "args", ")", "end" ]
Returns the absolute url including the passed protocol and host. This uses the same arguments as the url method, with added requirements of protocol and host options. :api: public
[ "Returns", "the", "absolute", "url", "including", "the", "passed", "protocol", "and", "host", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/abstract_controller.rb#L557-L570
train
wycats/merb
merb-core/lib/merb-core/controller/abstract_controller.rb
Merb.AbstractController.capture
def capture(*args, &block) ret = nil captured = send("capture_#{@_engine}", *args) do |*args| ret = yield *args end # return captured value only if it is not empty captured.empty? ? ret.to_s : captured end
ruby
def capture(*args, &block) ret = nil captured = send("capture_#{@_engine}", *args) do |*args| ret = yield *args end # return captured value only if it is not empty captured.empty? ? ret.to_s : captured end
[ "def", "capture", "(", "*", "args", ",", "&", "block", ")", "ret", "=", "nil", "captured", "=", "send", "(", "\"capture_#{@_engine}\"", ",", "*", "args", ")", "do", "|", "*", "args", "|", "ret", "=", "yield", "*", "args", "end", "captured", ".", "empty?", "?", "ret", ".", "to_s", ":", "captured", "end" ]
Calls the capture method for the selected template engine. ==== Parameters *args:: Arguments to pass to the block. &block:: The block to call. ==== Returns String:: The output of a template block or the return value of a non-template block converted to a string. :api: public
[ "Calls", "the", "capture", "method", "for", "the", "selected", "template", "engine", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/abstract_controller.rb#L616-L625
train
wycats/merb
merb-exceptions/lib/merb-exceptions/exceptions_helper.rb
MerbExceptions.ExceptionsHelper.notify_of_exceptions
def notify_of_exceptions if Merb::Plugins.config[:exceptions][:environments].include?(Merb.env) begin request = self.request details = {} details['exceptions'] = request.exceptions details['params'] = params details['params'] = self.class._filter_params(params) details['environment'] = request.env.merge( 'process' => $$ ) details['url'] = "#{request.protocol}#{request.env["HTTP_HOST"]}#{request.uri}" MerbExceptions::Notification.new(details).deliver! rescue Exception => e exceptions = request.exceptions << e Merb.logger.fatal!("Exception Notification Failed:\n" + (exceptions).inspect) File.open(Merb.root / 'log' / 'notification_errors.log', 'a') do |log| log.puts("Exception Notification Failed:") exceptions.each do |e| log.puts(Merb.exception(e)) end end end end end
ruby
def notify_of_exceptions if Merb::Plugins.config[:exceptions][:environments].include?(Merb.env) begin request = self.request details = {} details['exceptions'] = request.exceptions details['params'] = params details['params'] = self.class._filter_params(params) details['environment'] = request.env.merge( 'process' => $$ ) details['url'] = "#{request.protocol}#{request.env["HTTP_HOST"]}#{request.uri}" MerbExceptions::Notification.new(details).deliver! rescue Exception => e exceptions = request.exceptions << e Merb.logger.fatal!("Exception Notification Failed:\n" + (exceptions).inspect) File.open(Merb.root / 'log' / 'notification_errors.log', 'a') do |log| log.puts("Exception Notification Failed:") exceptions.each do |e| log.puts(Merb.exception(e)) end end end end end
[ "def", "notify_of_exceptions", "if", "Merb", "::", "Plugins", ".", "config", "[", ":exceptions", "]", "[", ":environments", "]", ".", "include?", "(", "Merb", ".", "env", ")", "begin", "request", "=", "self", ".", "request", "details", "=", "{", "}", "details", "[", "'exceptions'", "]", "=", "request", ".", "exceptions", "details", "[", "'params'", "]", "=", "params", "details", "[", "'params'", "]", "=", "self", ".", "class", ".", "_filter_params", "(", "params", ")", "details", "[", "'environment'", "]", "=", "request", ".", "env", ".", "merge", "(", "'process'", "=>", "$$", ")", "details", "[", "'url'", "]", "=", "\"#{request.protocol}#{request.env[\"HTTP_HOST\"]}#{request.uri}\"", "MerbExceptions", "::", "Notification", ".", "new", "(", "details", ")", ".", "deliver!", "rescue", "Exception", "=>", "e", "exceptions", "=", "request", ".", "exceptions", "<<", "e", "Merb", ".", "logger", ".", "fatal!", "(", "\"Exception Notification Failed:\\n\"", "+", "(", "exceptions", ")", ".", "inspect", ")", "File", ".", "open", "(", "Merb", ".", "root", "/", "'log'", "/", "'notification_errors.log'", ",", "'a'", ")", "do", "|", "log", "|", "log", ".", "puts", "(", "\"Exception Notification Failed:\"", ")", "exceptions", ".", "each", "do", "|", "e", "|", "log", ".", "puts", "(", "Merb", ".", "exception", "(", "e", ")", ")", "end", "end", "end", "end", "end" ]
if you need to handle the render yourself for some reason, you can call this method directly. It sends notifications without any rendering logic. Note though that if you are sending lots of notifications this could delay sending a response back to the user so try to avoid using it where possible.
[ "if", "you", "need", "to", "handle", "the", "render", "yourself", "for", "some", "reason", "you", "can", "call", "this", "method", "directly", ".", "It", "sends", "notifications", "without", "any", "rendering", "logic", ".", "Note", "though", "that", "if", "you", "are", "sending", "lots", "of", "notifications", "this", "could", "delay", "sending", "a", "response", "back", "to", "the", "user", "so", "try", "to", "avoid", "using", "it", "where", "possible", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-exceptions/lib/merb-exceptions/exceptions_helper.rb#L9-L32
train
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.writable?
def writable?(key, parameters = {}, conditions = {}) case key when String, Numeric, Symbol !conditions.has_key?(:expire_in) else nil end end
ruby
def writable?(key, parameters = {}, conditions = {}) case key when String, Numeric, Symbol !conditions.has_key?(:expire_in) else nil end end
[ "def", "writable?", "(", "key", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "case", "key", "when", "String", ",", "Numeric", ",", "Symbol", "!", "conditions", ".", "has_key?", "(", ":expire_in", ")", "else", "nil", "end", "end" ]
Creates directory for cached files unless it exists. File caching does not support expiration time.
[ "Creates", "directory", "for", "cached", "files", "unless", "it", "exists", ".", "File", "caching", "does", "not", "support", "expiration", "time", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L20-L26
train
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.read
def read(key, parameters = {}) if exists?(key, parameters) read_file(pathify(key, parameters)) end end
ruby
def read(key, parameters = {}) if exists?(key, parameters) read_file(pathify(key, parameters)) end end
[ "def", "read", "(", "key", ",", "parameters", "=", "{", "}", ")", "if", "exists?", "(", "key", ",", "parameters", ")", "read_file", "(", "pathify", "(", "key", ",", "parameters", ")", ")", "end", "end" ]
Reads cached template from disk if it exists.
[ "Reads", "cached", "template", "from", "disk", "if", "it", "exists", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L29-L33
train
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.write
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) if File.file?(path = pathify(key, parameters)) write_file(path, data) else create_path(path) && write_file(path, data) end end end
ruby
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) if File.file?(path = pathify(key, parameters)) write_file(path, data) else create_path(path) && write_file(path, data) end end end
[ "def", "write", "(", "key", ",", "data", "=", "nil", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "if", "writable?", "(", "key", ",", "parameters", ",", "conditions", ")", "if", "File", ".", "file?", "(", "path", "=", "pathify", "(", "key", ",", "parameters", ")", ")", "write_file", "(", "path", ",", "data", ")", "else", "create_path", "(", "path", ")", "&&", "write_file", "(", "path", ",", "data", ")", "end", "end", "end" ]
Writes cached template to disk, creating cache directory if it does not exist.
[ "Writes", "cached", "template", "to", "disk", "creating", "cache", "directory", "if", "it", "does", "not", "exist", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L37-L45
train
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.fetch
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || (writable?(key, parameters, conditions) && write(key, value = blk.call, parameters, conditions) && value) end
ruby
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || (writable?(key, parameters, conditions) && write(key, value = blk.call, parameters, conditions) && value) end
[ "def", "fetch", "(", "key", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ",", "&", "blk", ")", "read", "(", "key", ",", "parameters", ")", "||", "(", "writable?", "(", "key", ",", "parameters", ",", "conditions", ")", "&&", "write", "(", "key", ",", "value", "=", "blk", ".", "call", ",", "parameters", ",", "conditions", ")", "&&", "value", ")", "end" ]
Fetches cached data by key if it exists. If it does not, uses passed block to get new cached value and writes it using given key.
[ "Fetches", "cached", "data", "by", "key", "if", "it", "exists", ".", "If", "it", "does", "not", "uses", "passed", "block", "to", "get", "new", "cached", "value", "and", "writes", "it", "using", "given", "key", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L50-L52
train
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.read_file
def read_file(path) data = nil File.open(path, "r") do |file| file.flock(File::LOCK_EX) data = file.read file.flock(File::LOCK_UN) end data end
ruby
def read_file(path) data = nil File.open(path, "r") do |file| file.flock(File::LOCK_EX) data = file.read file.flock(File::LOCK_UN) end data end
[ "def", "read_file", "(", "path", ")", "data", "=", "nil", "File", ".", "open", "(", "path", ",", "\"r\"", ")", "do", "|", "file", "|", "file", ".", "flock", "(", "File", "::", "LOCK_EX", ")", "data", "=", "file", ".", "read", "file", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "end", "data", "end" ]
Reads file content. Access to the file uses file locking.
[ "Reads", "file", "content", ".", "Access", "to", "the", "file", "uses", "file", "locking", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L89-L98
train
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/file_store.rb
Merb::Cache.FileStore.write_file
def write_file(path, data) File.open(path, "w+") do |file| file.flock(File::LOCK_EX) file.write(data) file.flock(File::LOCK_UN) end true end
ruby
def write_file(path, data) File.open(path, "w+") do |file| file.flock(File::LOCK_EX) file.write(data) file.flock(File::LOCK_UN) end true end
[ "def", "write_file", "(", "path", ",", "data", ")", "File", ".", "open", "(", "path", ",", "\"w+\"", ")", "do", "|", "file", "|", "file", ".", "flock", "(", "File", "::", "LOCK_EX", ")", "file", ".", "write", "(", "data", ")", "file", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "end", "true", "end" ]
Writes file content. Access to the file uses file locking.
[ "Writes", "file", "content", ".", "Access", "to", "the", "file", "uses", "file", "locking", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/file_store.rb#L102-L110
train
wycats/merb
merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb
Merb::Cache.AdhocStore.write
def write(key, data = nil, parameters = {}, conditions = {}) @stores.capture_first {|s| s.write(key, data, parameters, conditions)} end
ruby
def write(key, data = nil, parameters = {}, conditions = {}) @stores.capture_first {|s| s.write(key, data, parameters, conditions)} end
[ "def", "write", "(", "key", ",", "data", "=", "nil", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "@stores", ".", "capture_first", "{", "|", "s", "|", "s", ".", "write", "(", "key", ",", "data", ",", "parameters", ",", "conditions", ")", "}", "end" ]
persists the data so that it can be retrieved by the key & parameters. returns nil if it is unable to persist the data. returns true if successful.
[ "persists", "the", "data", "so", "that", "it", "can", "be", "retrieved", "by", "the", "key", "&", "parameters", ".", "returns", "nil", "if", "it", "is", "unable", "to", "persist", "the", "data", ".", "returns", "true", "if", "successful", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb#L31-L33
train
wycats/merb
merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb
Merb::Cache.AdhocStore.write_all
def write_all(key, data = nil, parameters = {}, conditions = {}) @stores.map {|s| s.write_all(key, data, parameters, conditions)}.all? end
ruby
def write_all(key, data = nil, parameters = {}, conditions = {}) @stores.map {|s| s.write_all(key, data, parameters, conditions)}.all? end
[ "def", "write_all", "(", "key", ",", "data", "=", "nil", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "@stores", ".", "map", "{", "|", "s", "|", "s", ".", "write_all", "(", "key", ",", "data", ",", "parameters", ",", "conditions", ")", "}", ".", "all?", "end" ]
persists the data to all context stores. returns nil if none of the stores were able to persist the data. returns true if at least one write was successful.
[ "persists", "the", "data", "to", "all", "context", "stores", ".", "returns", "nil", "if", "none", "of", "the", "stores", "were", "able", "to", "persist", "the", "data", ".", "returns", "true", "if", "at", "least", "one", "write", "was", "successful", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb#L38-L40
train
wycats/merb
merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb
Merb::Cache.AdhocStore.fetch
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || @stores.capture_first {|s| s.fetch(key, parameters, conditions, &blk)} || blk.call end
ruby
def fetch(key, parameters = {}, conditions = {}, &blk) read(key, parameters) || @stores.capture_first {|s| s.fetch(key, parameters, conditions, &blk)} || blk.call end
[ "def", "fetch", "(", "key", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ",", "&", "blk", ")", "read", "(", "key", ",", "parameters", ")", "||", "@stores", ".", "capture_first", "{", "|", "s", "|", "s", ".", "fetch", "(", "key", ",", "parameters", ",", "conditions", ",", "&", "blk", ")", "}", "||", "blk", ".", "call", "end" ]
tries to read the data from the store. If that fails, it calls the block parameter and persists the result. If it cannot be fetched, the block call is returned.
[ "tries", "to", "read", "the", "data", "from", "the", "store", ".", "If", "that", "fails", "it", "calls", "the", "block", "parameter", "and", "persists", "the", "result", ".", "If", "it", "cannot", "be", "fetched", "the", "block", "call", "is", "returned", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb#L45-L49
train
wycats/merb
merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb
Merb::Cache.AdhocStore.delete
def delete(key, parameters = {}) @stores.map {|s| s.delete(key, parameters)}.any? end
ruby
def delete(key, parameters = {}) @stores.map {|s| s.delete(key, parameters)}.any? end
[ "def", "delete", "(", "key", ",", "parameters", "=", "{", "}", ")", "@stores", ".", "map", "{", "|", "s", "|", "s", ".", "delete", "(", "key", ",", "parameters", ")", "}", ".", "any?", "end" ]
deletes the entry for the key & parameter from the store.
[ "deletes", "the", "entry", "for", "the", "key", "&", "parameter", "from", "the", "store", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/strategy/adhoc_store.rb#L58-L60
train
wycats/merb
merb-auth/merb-auth-core/lib/merb-auth-core/authentication.rb
Merb.Authentication.user=
def user=(user) session[:user] = nil && return if user.nil? session[:user] = store_user(user) @user = session[:user] ? user : session[:user] end
ruby
def user=(user) session[:user] = nil && return if user.nil? session[:user] = store_user(user) @user = session[:user] ? user : session[:user] end
[ "def", "user", "=", "(", "user", ")", "session", "[", ":user", "]", "=", "nil", "&&", "return", "if", "user", ".", "nil?", "session", "[", ":user", "]", "=", "store_user", "(", "user", ")", "@user", "=", "session", "[", ":user", "]", "?", "user", ":", "session", "[", ":user", "]", "end" ]
This method will store the user provided into the session and set the user as the currently logged in user @return <User Class>|NilClass
[ "This", "method", "will", "store", "the", "user", "provided", "into", "the", "session", "and", "set", "the", "user", "as", "the", "currently", "logged", "in", "user" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-auth/merb-auth-core/lib/merb-auth-core/authentication.rb#L48-L52
train
wycats/merb
merb-auth/merb-auth-core/lib/merb-auth-core/authentication.rb
Merb.Authentication.authenticate!
def authenticate!(request, params, *rest) opts = rest.last.kind_of?(Hash) ? rest.pop : {} rest = rest.flatten strategies = if rest.empty? if request.session[:authentication_strategies] request.session[:authentication_strategies] else Merb::Authentication.default_strategy_order end else request.session[:authentication_strategies] ||= [] request.session[:authentication_strategies] << rest request.session[:authentication_strategies].flatten!.uniq! request.session[:authentication_strategies] end msg = opts[:message] || error_message user = nil # This one should find the first one that matches. It should not run antother strategies.detect do |s| s = Merb::Authentication.lookup_strategy[s] # Get the strategy from string or class unless s.abstract? strategy = s.new(request, params) user = strategy.run! if strategy.halted? self.headers, self.status, self.body = [strategy.headers, strategy.status, strategy.body] halt! return end user end end # Check after callbacks to make sure the user is still cool user = run_after_authentication_callbacks(user, request, params) if user # Finally, Raise an error if there is no user found, or set it in the session if there is. raise Merb::Controller::Unauthenticated, msg unless user session[:authentication_strategies] = nil # clear the session of Failed Strategies if login is successful self.user = user end
ruby
def authenticate!(request, params, *rest) opts = rest.last.kind_of?(Hash) ? rest.pop : {} rest = rest.flatten strategies = if rest.empty? if request.session[:authentication_strategies] request.session[:authentication_strategies] else Merb::Authentication.default_strategy_order end else request.session[:authentication_strategies] ||= [] request.session[:authentication_strategies] << rest request.session[:authentication_strategies].flatten!.uniq! request.session[:authentication_strategies] end msg = opts[:message] || error_message user = nil # This one should find the first one that matches. It should not run antother strategies.detect do |s| s = Merb::Authentication.lookup_strategy[s] # Get the strategy from string or class unless s.abstract? strategy = s.new(request, params) user = strategy.run! if strategy.halted? self.headers, self.status, self.body = [strategy.headers, strategy.status, strategy.body] halt! return end user end end # Check after callbacks to make sure the user is still cool user = run_after_authentication_callbacks(user, request, params) if user # Finally, Raise an error if there is no user found, or set it in the session if there is. raise Merb::Controller::Unauthenticated, msg unless user session[:authentication_strategies] = nil # clear the session of Failed Strategies if login is successful self.user = user end
[ "def", "authenticate!", "(", "request", ",", "params", ",", "*", "rest", ")", "opts", "=", "rest", ".", "last", ".", "kind_of?", "(", "Hash", ")", "?", "rest", ".", "pop", ":", "{", "}", "rest", "=", "rest", ".", "flatten", "strategies", "=", "if", "rest", ".", "empty?", "if", "request", ".", "session", "[", ":authentication_strategies", "]", "request", ".", "session", "[", ":authentication_strategies", "]", "else", "Merb", "::", "Authentication", ".", "default_strategy_order", "end", "else", "request", ".", "session", "[", ":authentication_strategies", "]", "||=", "[", "]", "request", ".", "session", "[", ":authentication_strategies", "]", "<<", "rest", "request", ".", "session", "[", ":authentication_strategies", "]", ".", "flatten!", ".", "uniq!", "request", ".", "session", "[", ":authentication_strategies", "]", "end", "msg", "=", "opts", "[", ":message", "]", "||", "error_message", "user", "=", "nil", "strategies", ".", "detect", "do", "|", "s", "|", "s", "=", "Merb", "::", "Authentication", ".", "lookup_strategy", "[", "s", "]", "unless", "s", ".", "abstract?", "strategy", "=", "s", ".", "new", "(", "request", ",", "params", ")", "user", "=", "strategy", ".", "run!", "if", "strategy", ".", "halted?", "self", ".", "headers", ",", "self", ".", "status", ",", "self", ".", "body", "=", "[", "strategy", ".", "headers", ",", "strategy", ".", "status", ",", "strategy", ".", "body", "]", "halt!", "return", "end", "user", "end", "end", "user", "=", "run_after_authentication_callbacks", "(", "user", ",", "request", ",", "params", ")", "if", "user", "raise", "Merb", "::", "Controller", "::", "Unauthenticated", ",", "msg", "unless", "user", "session", "[", ":authentication_strategies", "]", "=", "nil", "self", ".", "user", "=", "user", "end" ]
The workhorse of the framework. The authentiate! method is where the work is done. authenticate! will try each strategy in order either passed in, or in the default_strategy_order. If a strategy returns some kind of user object, this will be stored in the session, otherwise a Merb::Controller::Unauthenticated exception is raised @params Merb::Request, [List,Of,Strategies, optional_options_hash] Pass in a list of strategy objects to have this list take precedence over the normal defaults Use an options hash to provide an error message to be passed into the exception. @return user object of the verified user. An exception is raised if no user is found
[ "The", "workhorse", "of", "the", "framework", ".", "The", "authentiate!", "method", "is", "where", "the", "work", "is", "done", ".", "authenticate!", "will", "try", "each", "strategy", "in", "order", "either", "passed", "in", "or", "in", "the", "default_strategy_order", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-auth/merb-auth-core/lib/merb-auth-core/authentication.rb#L69-L110
train
wycats/merb
merb-core/lib/merb-core/dispatch/cookies.rb
Merb.Cookies.extract_headers
def extract_headers(controller_defaults = {}) defaults = @_cookie_defaults.merge(controller_defaults) cookies = [] self.each do |name, value| # Only set cookies that marked for inclusion in the response header. next unless @_options_lookup[name] options = defaults.merge(@_options_lookup[name]) if (expiry = options["expires"]).respond_to?(:gmtime) options["expires"] = expiry.gmtime.strftime(Merb::Const::COOKIE_EXPIRATION_FORMAT) end secure = options.delete("secure") http_only = options.delete("http_only") kookie = "#{name}=#{Merb::Parse.escape(value)}; " # WebKit in particular doens't like empty cookie options - skip them. options.each { |k, v| kookie << "#{k}=#{v}; " unless v.blank? } kookie << 'secure; ' if secure kookie << 'HttpOnly; ' if http_only cookies << kookie.rstrip end cookies.empty? ? {} : { 'Set-Cookie' => cookies } end
ruby
def extract_headers(controller_defaults = {}) defaults = @_cookie_defaults.merge(controller_defaults) cookies = [] self.each do |name, value| # Only set cookies that marked for inclusion in the response header. next unless @_options_lookup[name] options = defaults.merge(@_options_lookup[name]) if (expiry = options["expires"]).respond_to?(:gmtime) options["expires"] = expiry.gmtime.strftime(Merb::Const::COOKIE_EXPIRATION_FORMAT) end secure = options.delete("secure") http_only = options.delete("http_only") kookie = "#{name}=#{Merb::Parse.escape(value)}; " # WebKit in particular doens't like empty cookie options - skip them. options.each { |k, v| kookie << "#{k}=#{v}; " unless v.blank? } kookie << 'secure; ' if secure kookie << 'HttpOnly; ' if http_only cookies << kookie.rstrip end cookies.empty? ? {} : { 'Set-Cookie' => cookies } end
[ "def", "extract_headers", "(", "controller_defaults", "=", "{", "}", ")", "defaults", "=", "@_cookie_defaults", ".", "merge", "(", "controller_defaults", ")", "cookies", "=", "[", "]", "self", ".", "each", "do", "|", "name", ",", "value", "|", "next", "unless", "@_options_lookup", "[", "name", "]", "options", "=", "defaults", ".", "merge", "(", "@_options_lookup", "[", "name", "]", ")", "if", "(", "expiry", "=", "options", "[", "\"expires\"", "]", ")", ".", "respond_to?", "(", ":gmtime", ")", "options", "[", "\"expires\"", "]", "=", "expiry", ".", "gmtime", ".", "strftime", "(", "Merb", "::", "Const", "::", "COOKIE_EXPIRATION_FORMAT", ")", "end", "secure", "=", "options", ".", "delete", "(", "\"secure\"", ")", "http_only", "=", "options", ".", "delete", "(", "\"http_only\"", ")", "kookie", "=", "\"#{name}=#{Merb::Parse.escape(value)}; \"", "options", ".", "each", "{", "|", "k", ",", "v", "|", "kookie", "<<", "\"#{k}=#{v}; \"", "unless", "v", ".", "blank?", "}", "kookie", "<<", "'secure; '", "if", "secure", "kookie", "<<", "'HttpOnly; '", "if", "http_only", "cookies", "<<", "kookie", ".", "rstrip", "end", "cookies", ".", "empty?", "?", "{", "}", ":", "{", "'Set-Cookie'", "=>", "cookies", "}", "end" ]
Generate any necessary headers. ==== Returns Hash:: The headers to set, or an empty array if no cookies are set. :api: private
[ "Generate", "any", "necessary", "headers", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/cookies.rb#L70-L90
train
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/memcached_store.rb
Merb::Cache.MemcachedStore.read
def read(key, parameters = {}) begin @memcached.get(normalize(key, parameters)) rescue Memcached::NotFound, Memcached::Stored nil end end
ruby
def read(key, parameters = {}) begin @memcached.get(normalize(key, parameters)) rescue Memcached::NotFound, Memcached::Stored nil end end
[ "def", "read", "(", "key", ",", "parameters", "=", "{", "}", ")", "begin", "@memcached", ".", "get", "(", "normalize", "(", "key", ",", "parameters", ")", ")", "rescue", "Memcached", "::", "NotFound", ",", "Memcached", "::", "Stored", "nil", "end", "end" ]
Reads key from the cache.
[ "Reads", "key", "from", "the", "cache", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/memcached_store.rb#L25-L31
train
wycats/merb
merb-cache/lib/merb-cache/stores/fundamental/memcached_store.rb
Merb::Cache.MemcachedStore.write
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) begin @memcached.set(normalize(key, parameters), data, expire_time(conditions)) true rescue nil end end end
ruby
def write(key, data = nil, parameters = {}, conditions = {}) if writable?(key, parameters, conditions) begin @memcached.set(normalize(key, parameters), data, expire_time(conditions)) true rescue nil end end end
[ "def", "write", "(", "key", ",", "data", "=", "nil", ",", "parameters", "=", "{", "}", ",", "conditions", "=", "{", "}", ")", "if", "writable?", "(", "key", ",", "parameters", ",", "conditions", ")", "begin", "@memcached", ".", "set", "(", "normalize", "(", "key", ",", "parameters", ")", ",", "data", ",", "expire_time", "(", "conditions", ")", ")", "true", "rescue", "nil", "end", "end", "end" ]
Writes data to the cache using key, parameters and conditions.
[ "Writes", "data", "to", "the", "cache", "using", "key", "parameters", "and", "conditions", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-cache/lib/merb-cache/stores/fundamental/memcached_store.rb#L34-L43
train
wycats/merb
merb-assets/lib/merb-assets/assets_mixin.rb
Merb.AssetsMixin.extract_required_files
def extract_required_files(files, options = {}) return [] if files.nil? || files.empty? seen = [] files.inject([]) do |extracted, req_js| include_files, include_options = if req_js.last.is_a?(Hash) [req_js[0..-2], options.merge(req_js.last)] else [req_js, options] end seen += (includes = include_files - seen) extracted << (includes + [include_options]) unless includes.empty? extracted end end
ruby
def extract_required_files(files, options = {}) return [] if files.nil? || files.empty? seen = [] files.inject([]) do |extracted, req_js| include_files, include_options = if req_js.last.is_a?(Hash) [req_js[0..-2], options.merge(req_js.last)] else [req_js, options] end seen += (includes = include_files - seen) extracted << (includes + [include_options]) unless includes.empty? extracted end end
[ "def", "extract_required_files", "(", "files", ",", "options", "=", "{", "}", ")", "return", "[", "]", "if", "files", ".", "nil?", "||", "files", ".", "empty?", "seen", "=", "[", "]", "files", ".", "inject", "(", "[", "]", ")", "do", "|", "extracted", ",", "req_js", "|", "include_files", ",", "include_options", "=", "if", "req_js", ".", "last", ".", "is_a?", "(", "Hash", ")", "[", "req_js", "[", "0", "..", "-", "2", "]", ",", "options", ".", "merge", "(", "req_js", ".", "last", ")", "]", "else", "[", "req_js", ",", "options", "]", "end", "seen", "+=", "(", "includes", "=", "include_files", "-", "seen", ")", "extracted", "<<", "(", "includes", "+", "[", "include_options", "]", ")", "unless", "includes", ".", "empty?", "extracted", "end", "end" ]
Helper method to filter out duplicate files. ==== Parameters options<Hash>:: Options to pass to include tag methods.
[ "Helper", "method", "to", "filter", "out", "duplicate", "files", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-assets/lib/merb-assets/assets_mixin.rb#L742-L755
train
wycats/merb
merb-core/lib/merb-core/dispatch/session/memory.rb
Merb.MemorySessionStore.reap_expired_sessions
def reap_expired_sessions @timestamps.each do |session_id,stamp| delete_session(session_id) if (stamp + @session_ttl) < Time.now end GC.start end
ruby
def reap_expired_sessions @timestamps.each do |session_id,stamp| delete_session(session_id) if (stamp + @session_ttl) < Time.now end GC.start end
[ "def", "reap_expired_sessions", "@timestamps", ".", "each", "do", "|", "session_id", ",", "stamp", "|", "delete_session", "(", "session_id", ")", "if", "(", "stamp", "+", "@session_ttl", ")", "<", "Time", ".", "now", "end", "GC", ".", "start", "end" ]
Deletes any sessions that have reached their maximum validity. :api: private
[ "Deletes", "any", "sessions", "that", "have", "reached", "their", "maximum", "validity", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/memory.rb#L92-L97
train
wycats/merb
merb-core/lib/merb-core/dispatch/session/cookie.rb
Merb.CookieSession.to_cookie
def to_cookie unless self.empty? data = self.serialize value = Merb::Parse.escape "#{data}--#{generate_digest(data)}" if value.size > MAX msg = "Cookies have limit of 4K. Session contents: #{data.inspect}" Merb.logger.error!(msg) raise CookieOverflow, msg end value end end
ruby
def to_cookie unless self.empty? data = self.serialize value = Merb::Parse.escape "#{data}--#{generate_digest(data)}" if value.size > MAX msg = "Cookies have limit of 4K. Session contents: #{data.inspect}" Merb.logger.error!(msg) raise CookieOverflow, msg end value end end
[ "def", "to_cookie", "unless", "self", ".", "empty?", "data", "=", "self", ".", "serialize", "value", "=", "Merb", "::", "Parse", ".", "escape", "\"#{data}--#{generate_digest(data)}\"", "if", "value", ".", "size", ">", "MAX", "msg", "=", "\"Cookies have limit of 4K. Session contents: #{data.inspect}\"", "Merb", ".", "logger", ".", "error!", "(", "msg", ")", "raise", "CookieOverflow", ",", "msg", "end", "value", "end", "end" ]
Create the raw cookie string; includes an HMAC keyed message digest. ==== Returns String:: Cookie value. ==== Raises CookieOverflow:: More than 4K of data put into session. ==== Notes Session data is converted to a Hash first, since a container might choose to marshal it, which would make it persist attributes like 'needs_new_cookie', which it shouldn't. :api: private
[ "Create", "the", "raw", "cookie", "string", ";", "includes", "an", "HMAC", "keyed", "message", "digest", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/cookie.rb#L127-L138
train
wycats/merb
merb-core/lib/merb-core/dispatch/session/cookie.rb
Merb.CookieSession.secure_compare
def secure_compare(a, b) if a.length == b.length # unpack to forty characters. # needed for 1.8 and 1.9 compat a_bytes = a.unpack('C*') b_bytes = b.unpack('C*') result = 0 for i in 0..(a_bytes.length - 1) result |= a_bytes[i] ^ b_bytes[i] end result == 0 else false end end
ruby
def secure_compare(a, b) if a.length == b.length # unpack to forty characters. # needed for 1.8 and 1.9 compat a_bytes = a.unpack('C*') b_bytes = b.unpack('C*') result = 0 for i in 0..(a_bytes.length - 1) result |= a_bytes[i] ^ b_bytes[i] end result == 0 else false end end
[ "def", "secure_compare", "(", "a", ",", "b", ")", "if", "a", ".", "length", "==", "b", ".", "length", "a_bytes", "=", "a", ".", "unpack", "(", "'C*'", ")", "b_bytes", "=", "b", ".", "unpack", "(", "'C*'", ")", "result", "=", "0", "for", "i", "in", "0", "..", "(", "a_bytes", ".", "length", "-", "1", ")", "result", "|=", "a_bytes", "[", "i", "]", "^", "b_bytes", "[", "i", "]", "end", "result", "==", "0", "else", "false", "end", "end" ]
Securely compare two digests using a constant time algorithm. This avoids leaking information about the calculated HMAC Based on code by Michael Koziarski <[email protected]> http://github.com/rails/rails/commit/674f780d59a5a7ec0301755d43a7b277a3ad2978 ==== Parameters a, b<~to_s>:: digests to compare. ==== Returns Boolean:: Do the digests validate?
[ "Securely", "compare", "two", "digests", "using", "a", "constant", "time", "algorithm", ".", "This", "avoids", "leaking", "information", "about", "the", "calculated", "HMAC" ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/cookie.rb#L163-L179
train
wycats/merb
merb-core/lib/merb-core/dispatch/session/cookie.rb
Merb.CookieSession.unmarshal
def unmarshal(cookie) if cookie.blank? {} else data, digest = Merb::Parse.unescape(cookie).split('--') return {} if data.blank? || digest.blank? unless secure_compare(generate_digest(data), digest) clear unless Merb::Config[:ignore_tampered_cookies] raise TamperedWithCookie, "Maybe the site's session_secret_key has changed?" end end unserialize(data) end end
ruby
def unmarshal(cookie) if cookie.blank? {} else data, digest = Merb::Parse.unescape(cookie).split('--') return {} if data.blank? || digest.blank? unless secure_compare(generate_digest(data), digest) clear unless Merb::Config[:ignore_tampered_cookies] raise TamperedWithCookie, "Maybe the site's session_secret_key has changed?" end end unserialize(data) end end
[ "def", "unmarshal", "(", "cookie", ")", "if", "cookie", ".", "blank?", "{", "}", "else", "data", ",", "digest", "=", "Merb", "::", "Parse", ".", "unescape", "(", "cookie", ")", ".", "split", "(", "'--'", ")", "return", "{", "}", "if", "data", ".", "blank?", "||", "digest", ".", "blank?", "unless", "secure_compare", "(", "generate_digest", "(", "data", ")", ",", "digest", ")", "clear", "unless", "Merb", "::", "Config", "[", ":ignore_tampered_cookies", "]", "raise", "TamperedWithCookie", ",", "\"Maybe the site's session_secret_key has changed?\"", "end", "end", "unserialize", "(", "data", ")", "end", "end" ]
Unmarshal cookie data to a hash and verify its integrity. ==== Parameters cookie<~to_s>:: The cookie to unmarshal. ==== Raises TamperedWithCookie:: The digests don't match. ==== Returns Hash:: The stored session data. :api: private
[ "Unmarshal", "cookie", "data", "to", "a", "hash", "and", "verify", "its", "integrity", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/session/cookie.rb#L194-L208
train
wycats/merb
merb-core/lib/merb-core/dispatch/request.rb
Merb.Request.controller
def controller unless params[:controller] raise ControllerExceptions::NotFound, "Route matched, but route did not specify a controller.\n" + "Did you forgot to add :controller => \"people\" or :controller " + "segment to route definition?\nHere is what's specified:\n" + route.inspect end path = [params[:namespace], params[:controller]].compact.join(Merb::Const::SLASH) controller = path.snake_case.to_const_string begin Object.full_const_get(controller) rescue NameError => e msg = "Controller class not found for controller `#{path}'" Merb.logger.warn!(msg) raise ControllerExceptions::NotFound, msg end end
ruby
def controller unless params[:controller] raise ControllerExceptions::NotFound, "Route matched, but route did not specify a controller.\n" + "Did you forgot to add :controller => \"people\" or :controller " + "segment to route definition?\nHere is what's specified:\n" + route.inspect end path = [params[:namespace], params[:controller]].compact.join(Merb::Const::SLASH) controller = path.snake_case.to_const_string begin Object.full_const_get(controller) rescue NameError => e msg = "Controller class not found for controller `#{path}'" Merb.logger.warn!(msg) raise ControllerExceptions::NotFound, msg end end
[ "def", "controller", "unless", "params", "[", ":controller", "]", "raise", "ControllerExceptions", "::", "NotFound", ",", "\"Route matched, but route did not specify a controller.\\n\"", "+", "\"Did you forgot to add :controller => \\\"people\\\" or :controller \"", "+", "\"segment to route definition?\\nHere is what's specified:\\n\"", "+", "route", ".", "inspect", "end", "path", "=", "[", "params", "[", ":namespace", "]", ",", "params", "[", ":controller", "]", "]", ".", "compact", ".", "join", "(", "Merb", "::", "Const", "::", "SLASH", ")", "controller", "=", "path", ".", "snake_case", ".", "to_const_string", "begin", "Object", ".", "full_const_get", "(", "controller", ")", "rescue", "NameError", "=>", "e", "msg", "=", "\"Controller class not found for controller `#{path}'\"", "Merb", ".", "logger", ".", "warn!", "(", "msg", ")", "raise", "ControllerExceptions", "::", "NotFound", ",", "msg", "end", "end" ]
Returns the controller object for initialization and dispatching the request. ==== Returns Class:: The controller class matching the routed request, e.g. Posts. :api: private
[ "Returns", "the", "controller", "object", "for", "initialization", "and", "dispatching", "the", "request", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/request.rb#L69-L87
train
wycats/merb
merb-core/lib/merb-core/dispatch/request.rb
Merb.Request.body_params
def body_params @body_params ||= begin if content_type && content_type.match(Merb::Const::FORM_URL_ENCODED_REGEXP) # or content_type.nil? Merb::Parse.query(raw_post) end end end
ruby
def body_params @body_params ||= begin if content_type && content_type.match(Merb::Const::FORM_URL_ENCODED_REGEXP) # or content_type.nil? Merb::Parse.query(raw_post) end end end
[ "def", "body_params", "@body_params", "||=", "begin", "if", "content_type", "&&", "content_type", ".", "match", "(", "Merb", "::", "Const", "::", "FORM_URL_ENCODED_REGEXP", ")", "Merb", "::", "Parse", ".", "query", "(", "raw_post", ")", "end", "end", "end" ]
Parameters passed in the body of the request. Ajax calls from prototype.js and other libraries pass content this way. ==== Returns Hash:: The parameters passed in the body. :api: private
[ "Parameters", "passed", "in", "the", "body", "of", "the", "request", ".", "Ajax", "calls", "from", "prototype", ".", "js", "and", "other", "libraries", "pass", "content", "this", "way", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/dispatch/request.rb#L217-L223
train
wycats/merb
merb-auth/merb-auth-core/lib/merb-auth-core/authenticated_helper.rb
Merb.AuthenticatedHelper.ensure_authenticated
def ensure_authenticated(*strategies) session.authenticate!(request, params, *strategies) unless session.authenticated? auth = session.authentication if auth.halted? self.headers.merge!(auth.headers) self.status = auth.status throw :halt, auth.body end session.user end
ruby
def ensure_authenticated(*strategies) session.authenticate!(request, params, *strategies) unless session.authenticated? auth = session.authentication if auth.halted? self.headers.merge!(auth.headers) self.status = auth.status throw :halt, auth.body end session.user end
[ "def", "ensure_authenticated", "(", "*", "strategies", ")", "session", ".", "authenticate!", "(", "request", ",", "params", ",", "*", "strategies", ")", "unless", "session", ".", "authenticated?", "auth", "=", "session", ".", "authentication", "if", "auth", ".", "halted?", "self", ".", "headers", ".", "merge!", "(", "auth", ".", "headers", ")", "self", ".", "status", "=", "auth", ".", "status", "throw", ":halt", ",", "auth", ".", "body", "end", "session", ".", "user", "end" ]
This is the main method to use as a before filter. You can call it with options and strategies to use. It will check if a user is logged in, and failing that will run through either specified. @params all are optional. A list of strategies, optionally followed by a options hash. If used with no options, or only the hash, the default strategies will be used see Authentictaion.default_strategy_order. If a list of strategies is passed in, the default strategies are ignored, and the passed in strategies are used in order until either one is found, or all fail. A failed login will result in an Unauthenticated exception being raised. Use the :message key in the options hash to pass in a failure message to the exception. === Example class MyController < Application before :ensure_authenticated, :with => [OpenID,FormPassword, :message => "Failz!"] #... <snip> end
[ "This", "is", "the", "main", "method", "to", "use", "as", "a", "before", "filter", ".", "You", "can", "call", "it", "with", "options", "and", "strategies", "to", "use", ".", "It", "will", "check", "if", "a", "user", "is", "logged", "in", "and", "failing", "that", "will", "run", "through", "either", "specified", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-auth/merb-auth-core/lib/merb-auth-core/authenticated_helper.rb#L31-L40
train
danabr/multipart-parser
lib/multipart_parser/parser.rb
MultipartParser.Parser.callback
def callback(event, buffer = nil, start = nil, the_end = nil) return if !start.nil? && start == the_end if @callbacks.has_key? event @callbacks[event].call(buffer, start, the_end) end end
ruby
def callback(event, buffer = nil, start = nil, the_end = nil) return if !start.nil? && start == the_end if @callbacks.has_key? event @callbacks[event].call(buffer, start, the_end) end end
[ "def", "callback", "(", "event", ",", "buffer", "=", "nil", ",", "start", "=", "nil", ",", "the_end", "=", "nil", ")", "return", "if", "!", "start", ".", "nil?", "&&", "start", "==", "the_end", "if", "@callbacks", ".", "has_key?", "event", "@callbacks", "[", "event", "]", ".", "call", "(", "buffer", ",", "start", ",", "the_end", ")", "end", "end" ]
Issues a callback.
[ "Issues", "a", "callback", "." ]
b93890bb58de80d16c68bbb9131fcc140ca289fe
https://github.com/danabr/multipart-parser/blob/b93890bb58de80d16c68bbb9131fcc140ca289fe/lib/multipart_parser/parser.rb#L225-L230
train
wycats/merb
merb-core/lib/merb-core/controller/mixins/responder.rb
Merb.ResponderMixin.content_type=
def content_type=(type) unless Merb.available_mime_types.has_key?(type) raise Merb::ControllerExceptions::NotAcceptable.new("Unknown content_type for response: #{type}") end @_content_type = type mime = Merb.available_mime_types[type] headers["Content-Type"] = mime[:content_type] # merge any format specific response headers mime[:response_headers].each { |k,v| headers[k] ||= v } # if given, use a block to finetune any runtime headers mime[:response_block].call(self) if mime[:response_block] @_content_type end
ruby
def content_type=(type) unless Merb.available_mime_types.has_key?(type) raise Merb::ControllerExceptions::NotAcceptable.new("Unknown content_type for response: #{type}") end @_content_type = type mime = Merb.available_mime_types[type] headers["Content-Type"] = mime[:content_type] # merge any format specific response headers mime[:response_headers].each { |k,v| headers[k] ||= v } # if given, use a block to finetune any runtime headers mime[:response_block].call(self) if mime[:response_block] @_content_type end
[ "def", "content_type", "=", "(", "type", ")", "unless", "Merb", ".", "available_mime_types", ".", "has_key?", "(", "type", ")", "raise", "Merb", "::", "ControllerExceptions", "::", "NotAcceptable", ".", "new", "(", "\"Unknown content_type for response: #{type}\"", ")", "end", "@_content_type", "=", "type", "mime", "=", "Merb", ".", "available_mime_types", "[", "type", "]", "headers", "[", "\"Content-Type\"", "]", "=", "mime", "[", ":content_type", "]", "mime", "[", ":response_headers", "]", ".", "each", "{", "|", "k", ",", "v", "|", "headers", "[", "k", "]", "||=", "v", "}", "mime", "[", ":response_block", "]", ".", "call", "(", "self", ")", "if", "mime", "[", ":response_block", "]", "@_content_type", "end" ]
Sets the content type of the current response to a value based on a passed in key. The Content-Type header will be set to the first registered header for the mime-type. ==== Parameters type<Symbol>:: The content type. ==== Raises ArgumentError:: type is not in the list of registered mime-types. ==== Returns Symbol:: The content-type that was passed in. :api: plugin
[ "Sets", "the", "content", "type", "of", "the", "current", "response", "to", "a", "value", "based", "on", "a", "passed", "in", "key", ".", "The", "Content", "-", "Type", "header", "will", "be", "set", "to", "the", "first", "registered", "header", "for", "the", "mime", "-", "type", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-core/lib/merb-core/controller/mixins/responder.rb#L364-L382
train
wycats/merb
merb-mailer/lib/merb-mailer/mail_controller.rb
Merb.MailController.render_mail
def render_mail(options = @method) @_missing_templates = false # used to make sure that at least one template was found # If the options are not a hash, normalize to an action hash options = {:action => {:html => options, :text => options}} if !options.is_a?(Hash) # Take care of the options opts_hash = {} opts = options.dup actions = opts.delete(:action) if opts[:action].is_a?(Hash) templates = opts.delete(:template) if opts[:template].is_a?(Hash) # Prepare the options hash for each format # We need to delete anything relating to the other format here # before we try to render the template. [:html, :text].each do |fmt| opts_hash[fmt] = opts.delete(fmt) opts_hash[fmt] ||= actions[fmt] if actions && actions[fmt] opts_hash[:template] = templates[fmt] if templates && templates[fmt] end # Send the result to the mailer { :html => "rawhtml=", :text => "text="}.each do |fmt,meth| begin local_opts = opts.merge(:format => fmt) local_opts.merge!(:layout => false) if opts_hash[fmt].is_a?(String) clear_content value = render opts_hash[fmt], local_opts @mail.send(meth,value) unless value.nil? || value.empty? rescue Merb::ControllerExceptions::TemplateNotFound => e # An error should be logged if no template is found instead of an error raised if @_missing_templates Merb.logger.error(e.message) else @_missing_templates = true end end end @mail end
ruby
def render_mail(options = @method) @_missing_templates = false # used to make sure that at least one template was found # If the options are not a hash, normalize to an action hash options = {:action => {:html => options, :text => options}} if !options.is_a?(Hash) # Take care of the options opts_hash = {} opts = options.dup actions = opts.delete(:action) if opts[:action].is_a?(Hash) templates = opts.delete(:template) if opts[:template].is_a?(Hash) # Prepare the options hash for each format # We need to delete anything relating to the other format here # before we try to render the template. [:html, :text].each do |fmt| opts_hash[fmt] = opts.delete(fmt) opts_hash[fmt] ||= actions[fmt] if actions && actions[fmt] opts_hash[:template] = templates[fmt] if templates && templates[fmt] end # Send the result to the mailer { :html => "rawhtml=", :text => "text="}.each do |fmt,meth| begin local_opts = opts.merge(:format => fmt) local_opts.merge!(:layout => false) if opts_hash[fmt].is_a?(String) clear_content value = render opts_hash[fmt], local_opts @mail.send(meth,value) unless value.nil? || value.empty? rescue Merb::ControllerExceptions::TemplateNotFound => e # An error should be logged if no template is found instead of an error raised if @_missing_templates Merb.logger.error(e.message) else @_missing_templates = true end end end @mail end
[ "def", "render_mail", "(", "options", "=", "@method", ")", "@_missing_templates", "=", "false", "options", "=", "{", ":action", "=>", "{", ":html", "=>", "options", ",", ":text", "=>", "options", "}", "}", "if", "!", "options", ".", "is_a?", "(", "Hash", ")", "opts_hash", "=", "{", "}", "opts", "=", "options", ".", "dup", "actions", "=", "opts", ".", "delete", "(", ":action", ")", "if", "opts", "[", ":action", "]", ".", "is_a?", "(", "Hash", ")", "templates", "=", "opts", ".", "delete", "(", ":template", ")", "if", "opts", "[", ":template", "]", ".", "is_a?", "(", "Hash", ")", "[", ":html", ",", ":text", "]", ".", "each", "do", "|", "fmt", "|", "opts_hash", "[", "fmt", "]", "=", "opts", ".", "delete", "(", "fmt", ")", "opts_hash", "[", "fmt", "]", "||=", "actions", "[", "fmt", "]", "if", "actions", "&&", "actions", "[", "fmt", "]", "opts_hash", "[", ":template", "]", "=", "templates", "[", "fmt", "]", "if", "templates", "&&", "templates", "[", "fmt", "]", "end", "{", ":html", "=>", "\"rawhtml=\"", ",", ":text", "=>", "\"text=\"", "}", ".", "each", "do", "|", "fmt", ",", "meth", "|", "begin", "local_opts", "=", "opts", ".", "merge", "(", ":format", "=>", "fmt", ")", "local_opts", ".", "merge!", "(", ":layout", "=>", "false", ")", "if", "opts_hash", "[", "fmt", "]", ".", "is_a?", "(", "String", ")", "clear_content", "value", "=", "render", "opts_hash", "[", "fmt", "]", ",", "local_opts", "@mail", ".", "send", "(", "meth", ",", "value", ")", "unless", "value", ".", "nil?", "||", "value", ".", "empty?", "rescue", "Merb", "::", "ControllerExceptions", "::", "TemplateNotFound", "=>", "e", "if", "@_missing_templates", "Merb", ".", "logger", ".", "error", "(", "e", ".", "message", ")", "else", "@_missing_templates", "=", "true", "end", "end", "end", "@mail", "end" ]
Allows you to render various types of things into the text and HTML parts of an email If you include just text, the email will be sent as plain-text. If you include HTML, the email will be sent as a multi-part email. ==== Parameters options<~to_s, Hash>:: Options for rendering the email or an action name. See examples below for usage. ==== Examples There are a lot of ways to use render_mail, but it works similarly to the default Merb render method. First of all, you'll need to store email files in your app/mailers/views directory. They should be under a directory that matches the name of your mailer (e.g. TestMailer's views would be stored under test_mailer). The files themselves should be named action_name.mime_type.extension. For example, an erb template that should be the HTML part of the email, and rendered from the "foo" action would be named foo.html.erb. The only mime-types currently supported are "html" and "text", which correspond to text/html and text/plain respectively. All template systems supported by your app are available to MailController, and the extensions are the same as they are throughout the rest of Merb. render_mail can take any of the following option patterns: render_mail will attempt to render the current action. If the current action is "foo", this is identical to render_mail :foo. render_mail :foo checks for foo.html.ext and foo.text.ext and applies them as appropriate. render_mail :action => {:html => :foo, :text => :bar} checks for foo.html.ext and bar.text.ext in the view directory of the current controller and adds them to the mail object if found render_mail :template => {:html => "foo/bar", :text => "foo/baz"} checks for bar.html.ext and baz.text.ext in the foo directory and adds them to the mail object if found. render_mail :html => :foo, :text => :bar the same as render_mail :action => {html => :foo, :text => :bar } render_mail :html => "FOO", :text => "BAR" adds the text "FOO" as the html part of the email and the text "BAR" as the text part of the email. The difference between the last two examples is that symbols represent actions to render, while string represent the literal text to render. Note that you can use regular render methods instead of literal strings here, like: render_mail :html => render(:action => :foo) but you're probably better off just using render_mail :action at that point. You can also mix and match: render_mail :action => {:html => :foo}, :text => "BAR" which would be identical to: render_mail :html => :foo, :text => "BAR"
[ "Allows", "you", "to", "render", "various", "types", "of", "things", "into", "the", "text", "and", "HTML", "parts", "of", "an", "email", "If", "you", "include", "just", "text", "the", "email", "will", "be", "sent", "as", "plain", "-", "text", ".", "If", "you", "include", "HTML", "the", "email", "will", "be", "sent", "as", "a", "multi", "-", "part", "email", "." ]
b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39
https://github.com/wycats/merb/blob/b34d3d4fb6da70c2e9e9e56ddccc73f8a3e55e39/merb-mailer/lib/merb-mailer/mail_controller.rb#L212-L251
train
leonhartX/danger-lgtm
lib/lgtm/plugin.rb
Danger.DangerLgtm.check_lgtm
def check_lgtm(image_url: nil, https_image_only: false) return unless status_report[:errors].length.zero? && status_report[:warnings].length.zero? image_url ||= fetch_image_url(https_image_only: https_image_only) markdown( markdown_template(image_url) ) end
ruby
def check_lgtm(image_url: nil, https_image_only: false) return unless status_report[:errors].length.zero? && status_report[:warnings].length.zero? image_url ||= fetch_image_url(https_image_only: https_image_only) markdown( markdown_template(image_url) ) end
[ "def", "check_lgtm", "(", "image_url", ":", "nil", ",", "https_image_only", ":", "false", ")", "return", "unless", "status_report", "[", ":errors", "]", ".", "length", ".", "zero?", "&&", "status_report", "[", ":warnings", "]", ".", "length", ".", "zero?", "image_url", "||=", "fetch_image_url", "(", "https_image_only", ":", "https_image_only", ")", "markdown", "(", "markdown_template", "(", "image_url", ")", ")", "end" ]
Check status report, say lgtm if no violations Generates a `markdown` of a lgtm image. @param [String] image_url lgtm image url @param [Boolean] https_image_only https image only if true @return [void]
[ "Check", "status", "report", "say", "lgtm", "if", "no", "violations", "Generates", "a", "markdown", "of", "a", "lgtm", "image", "." ]
f45b3a588dd14906c590fd2fd28922b39f272088
https://github.com/leonhartX/danger-lgtm/blob/f45b3a588dd14906c590fd2fd28922b39f272088/lib/lgtm/plugin.rb#L32-L41
train
ruby-marc/ruby-marc
lib/marc/xml_parsers.rb
MARC.REXMLReader.each
def each unless block_given? return self.enum_for(:each) else while @parser.has_next? event = @parser.pull # if it's the start of a record element if event.start_element? and strip_ns(event[0]) == 'record' yield build_record end end end end
ruby
def each unless block_given? return self.enum_for(:each) else while @parser.has_next? event = @parser.pull # if it's the start of a record element if event.start_element? and strip_ns(event[0]) == 'record' yield build_record end end end end
[ "def", "each", "unless", "block_given?", "return", "self", ".", "enum_for", "(", ":each", ")", "else", "while", "@parser", ".", "has_next?", "event", "=", "@parser", ".", "pull", "if", "event", ".", "start_element?", "and", "strip_ns", "(", "event", "[", "0", "]", ")", "==", "'record'", "yield", "build_record", "end", "end", "end", "end" ]
Loop through the MARC records in the XML document
[ "Loop", "through", "the", "MARC", "records", "in", "the", "XML", "document" ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/xml_parsers.rb#L179-L191
train
ruby-marc/ruby-marc
lib/marc/xml_parsers.rb
MARC.REXMLReader.build_record
def build_record record = MARC::Record.new data_field = nil control_field = nil subfield = nil text = '' attrs = nil if Module.constants.index('Nokogiri') and @parser.is_a?(Nokogiri::XML::Reader) datafield = nil cursor = nil open_elements = [] @parser.each do | node | if node.value? && cursor if cursor.is_a?(Symbol) and cursor == :leader record.leader = node.value else cursor.value = node.value end cursor = nil end next unless node.namespace_uri == @ns if open_elements.index(node.local_name.downcase) open_elements.delete(node.local_name.downcase) next else open_elements << node.local_name.downcase end case node.local_name.downcase when "leader" cursor = :leader when "controlfield" record << datafield if datafield datafield = nil control_field = MARC::ControlField.new(node.attribute('tag')) record << control_field cursor = control_field when "datafield" record << datafield if datafield datafield = nil data_field = MARC::DataField.new(node.attribute('tag'), node.attribute('ind1'), node.attribute('ind2')) datafield = data_field when "subfield" raise "No datafield to add to" unless datafield subfield = MARC::Subfield.new(node.attribute('code')) datafield.append(subfield) cursor = subfield when "record" record << datafield if datafield return record end #puts node.name end else while @parser.has_next? event = @parser.pull if event.text? text += REXML::Text::unnormalize(event[0]) next end if event.start_element? text = '' attrs = event[1] case strip_ns(event[0]) when 'controlfield' text = '' control_field = MARC::ControlField.new(attrs['tag']) when 'datafield' text = '' data_field = MARC::DataField.new(attrs['tag'], attrs['ind1'], attrs['ind2']) when 'subfield' text = '' subfield = MARC::Subfield.new(attrs['code']) end end if event.end_element? case strip_ns(event[0]) when 'leader' record.leader = text when 'record' return record when 'controlfield' control_field.value = text record.append(control_field) when 'datafield' record.append(data_field) when 'subfield' subfield.value = text data_field.append(subfield) end end end end end
ruby
def build_record record = MARC::Record.new data_field = nil control_field = nil subfield = nil text = '' attrs = nil if Module.constants.index('Nokogiri') and @parser.is_a?(Nokogiri::XML::Reader) datafield = nil cursor = nil open_elements = [] @parser.each do | node | if node.value? && cursor if cursor.is_a?(Symbol) and cursor == :leader record.leader = node.value else cursor.value = node.value end cursor = nil end next unless node.namespace_uri == @ns if open_elements.index(node.local_name.downcase) open_elements.delete(node.local_name.downcase) next else open_elements << node.local_name.downcase end case node.local_name.downcase when "leader" cursor = :leader when "controlfield" record << datafield if datafield datafield = nil control_field = MARC::ControlField.new(node.attribute('tag')) record << control_field cursor = control_field when "datafield" record << datafield if datafield datafield = nil data_field = MARC::DataField.new(node.attribute('tag'), node.attribute('ind1'), node.attribute('ind2')) datafield = data_field when "subfield" raise "No datafield to add to" unless datafield subfield = MARC::Subfield.new(node.attribute('code')) datafield.append(subfield) cursor = subfield when "record" record << datafield if datafield return record end #puts node.name end else while @parser.has_next? event = @parser.pull if event.text? text += REXML::Text::unnormalize(event[0]) next end if event.start_element? text = '' attrs = event[1] case strip_ns(event[0]) when 'controlfield' text = '' control_field = MARC::ControlField.new(attrs['tag']) when 'datafield' text = '' data_field = MARC::DataField.new(attrs['tag'], attrs['ind1'], attrs['ind2']) when 'subfield' text = '' subfield = MARC::Subfield.new(attrs['code']) end end if event.end_element? case strip_ns(event[0]) when 'leader' record.leader = text when 'record' return record when 'controlfield' control_field.value = text record.append(control_field) when 'datafield' record.append(data_field) when 'subfield' subfield.value = text data_field.append(subfield) end end end end end
[ "def", "build_record", "record", "=", "MARC", "::", "Record", ".", "new", "data_field", "=", "nil", "control_field", "=", "nil", "subfield", "=", "nil", "text", "=", "''", "attrs", "=", "nil", "if", "Module", ".", "constants", ".", "index", "(", "'Nokogiri'", ")", "and", "@parser", ".", "is_a?", "(", "Nokogiri", "::", "XML", "::", "Reader", ")", "datafield", "=", "nil", "cursor", "=", "nil", "open_elements", "=", "[", "]", "@parser", ".", "each", "do", "|", "node", "|", "if", "node", ".", "value?", "&&", "cursor", "if", "cursor", ".", "is_a?", "(", "Symbol", ")", "and", "cursor", "==", ":leader", "record", ".", "leader", "=", "node", ".", "value", "else", "cursor", ".", "value", "=", "node", ".", "value", "end", "cursor", "=", "nil", "end", "next", "unless", "node", ".", "namespace_uri", "==", "@ns", "if", "open_elements", ".", "index", "(", "node", ".", "local_name", ".", "downcase", ")", "open_elements", ".", "delete", "(", "node", ".", "local_name", ".", "downcase", ")", "next", "else", "open_elements", "<<", "node", ".", "local_name", ".", "downcase", "end", "case", "node", ".", "local_name", ".", "downcase", "when", "\"leader\"", "cursor", "=", ":leader", "when", "\"controlfield\"", "record", "<<", "datafield", "if", "datafield", "datafield", "=", "nil", "control_field", "=", "MARC", "::", "ControlField", ".", "new", "(", "node", ".", "attribute", "(", "'tag'", ")", ")", "record", "<<", "control_field", "cursor", "=", "control_field", "when", "\"datafield\"", "record", "<<", "datafield", "if", "datafield", "datafield", "=", "nil", "data_field", "=", "MARC", "::", "DataField", ".", "new", "(", "node", ".", "attribute", "(", "'tag'", ")", ",", "node", ".", "attribute", "(", "'ind1'", ")", ",", "node", ".", "attribute", "(", "'ind2'", ")", ")", "datafield", "=", "data_field", "when", "\"subfield\"", "raise", "\"No datafield to add to\"", "unless", "datafield", "subfield", "=", "MARC", "::", "Subfield", ".", "new", "(", "node", ".", "attribute", "(", "'code'", ")", ")", "datafield", ".", "append", "(", "subfield", ")", "cursor", "=", "subfield", "when", "\"record\"", "record", "<<", "datafield", "if", "datafield", "return", "record", "end", "end", "else", "while", "@parser", ".", "has_next?", "event", "=", "@parser", ".", "pull", "if", "event", ".", "text?", "text", "+=", "REXML", "::", "Text", "::", "unnormalize", "(", "event", "[", "0", "]", ")", "next", "end", "if", "event", ".", "start_element?", "text", "=", "''", "attrs", "=", "event", "[", "1", "]", "case", "strip_ns", "(", "event", "[", "0", "]", ")", "when", "'controlfield'", "text", "=", "''", "control_field", "=", "MARC", "::", "ControlField", ".", "new", "(", "attrs", "[", "'tag'", "]", ")", "when", "'datafield'", "text", "=", "''", "data_field", "=", "MARC", "::", "DataField", ".", "new", "(", "attrs", "[", "'tag'", "]", ",", "attrs", "[", "'ind1'", "]", ",", "attrs", "[", "'ind2'", "]", ")", "when", "'subfield'", "text", "=", "''", "subfield", "=", "MARC", "::", "Subfield", ".", "new", "(", "attrs", "[", "'code'", "]", ")", "end", "end", "if", "event", ".", "end_element?", "case", "strip_ns", "(", "event", "[", "0", "]", ")", "when", "'leader'", "record", ".", "leader", "=", "text", "when", "'record'", "return", "record", "when", "'controlfield'", "control_field", ".", "value", "=", "text", "record", ".", "append", "(", "control_field", ")", "when", "'datafield'", "record", ".", "append", "(", "data_field", ")", "when", "'subfield'", "subfield", ".", "value", "=", "text", "data_field", ".", "append", "(", "subfield", ")", "end", "end", "end", "end", "end" ]
will accept parse events until a record has been built up
[ "will", "accept", "parse", "events", "until", "a", "record", "has", "been", "built", "up" ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/xml_parsers.rb#L200-L297
train
leonhartX/danger-lgtm
lib/lgtm/error_handleable.rb
Lgtm.ErrorHandleable.validate_response
def validate_response(response) case response when *SERVER_ERRORS raise ::Lgtm::Errors::UnexpectedError when *CLIENT_ERRORS raise ::Lgtm::Errors::UnexpectedError end end
ruby
def validate_response(response) case response when *SERVER_ERRORS raise ::Lgtm::Errors::UnexpectedError when *CLIENT_ERRORS raise ::Lgtm::Errors::UnexpectedError end end
[ "def", "validate_response", "(", "response", ")", "case", "response", "when", "*", "SERVER_ERRORS", "raise", "::", "Lgtm", "::", "Errors", "::", "UnexpectedError", "when", "*", "CLIENT_ERRORS", "raise", "::", "Lgtm", "::", "Errors", "::", "UnexpectedError", "end", "end" ]
validate_response is response validating @param [Net::HTTPxxx] response Net::HTTP responses @raise ::Lgtm::Errors::UnexpectedError @return [void]
[ "validate_response", "is", "response", "validating" ]
f45b3a588dd14906c590fd2fd28922b39f272088
https://github.com/leonhartX/danger-lgtm/blob/f45b3a588dd14906c590fd2fd28922b39f272088/lib/lgtm/error_handleable.rb#L24-L31
train
ruby-marc/ruby-marc
lib/marc/record.rb
MARC.FieldMap.reindex
def reindex @tags = {} self.each_with_index do |field, i| @tags[field.tag] ||= [] @tags[field.tag] << i end @clean = true end
ruby
def reindex @tags = {} self.each_with_index do |field, i| @tags[field.tag] ||= [] @tags[field.tag] << i end @clean = true end
[ "def", "reindex", "@tags", "=", "{", "}", "self", ".", "each_with_index", "do", "|", "field", ",", "i", "|", "@tags", "[", "field", ".", "tag", "]", "||=", "[", "]", "@tags", "[", "field", ".", "tag", "]", "<<", "i", "end", "@clean", "=", "true", "end" ]
Rebuild the HashWithChecksumAttribute with the current values of the fields Array
[ "Rebuild", "the", "HashWithChecksumAttribute", "with", "the", "current", "values", "of", "the", "fields", "Array" ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/record.rb#L17-L24
train
ruby-marc/ruby-marc
lib/marc/record.rb
MARC.Record.fields
def fields(filter=nil) unless filter # Since we're returning the FieldMap object, which the caller # may mutate, we precautionarily mark dirty -- unless it's frozen # immutable. @fields.clean = false unless @fields.frozen? return @fields end @fields.reindex unless @fields.clean flds = [] if filter.is_a?(String) && @fields.tags[filter] @fields.tags[filter].each do |idx| flds << @fields[idx] end elsif filter.is_a?(Array) || filter.is_a?(Range) @fields.each_by_tag(filter) do |tag| flds << tag end end flds end
ruby
def fields(filter=nil) unless filter # Since we're returning the FieldMap object, which the caller # may mutate, we precautionarily mark dirty -- unless it's frozen # immutable. @fields.clean = false unless @fields.frozen? return @fields end @fields.reindex unless @fields.clean flds = [] if filter.is_a?(String) && @fields.tags[filter] @fields.tags[filter].each do |idx| flds << @fields[idx] end elsif filter.is_a?(Array) || filter.is_a?(Range) @fields.each_by_tag(filter) do |tag| flds << tag end end flds end
[ "def", "fields", "(", "filter", "=", "nil", ")", "unless", "filter", "@fields", ".", "clean", "=", "false", "unless", "@fields", ".", "frozen?", "return", "@fields", "end", "@fields", ".", "reindex", "unless", "@fields", ".", "clean", "flds", "=", "[", "]", "if", "filter", ".", "is_a?", "(", "String", ")", "&&", "@fields", ".", "tags", "[", "filter", "]", "@fields", ".", "tags", "[", "filter", "]", ".", "each", "do", "|", "idx", "|", "flds", "<<", "@fields", "[", "idx", "]", "end", "elsif", "filter", ".", "is_a?", "(", "Array", ")", "||", "filter", ".", "is_a?", "(", "Range", ")", "@fields", ".", "each_by_tag", "(", "filter", ")", "do", "|", "tag", "|", "flds", "<<", "tag", "end", "end", "flds", "end" ]
Provides a backwards compatible means to access the FieldMap. No argument returns the FieldMap array in entirety. Providing a string, array or range of tags will return an array of fields in the order they appear in the record.
[ "Provides", "a", "backwards", "compatible", "means", "to", "access", "the", "FieldMap", ".", "No", "argument", "returns", "the", "FieldMap", "array", "in", "entirety", ".", "Providing", "a", "string", "array", "or", "range", "of", "tags", "will", "return", "an", "array", "of", "fields", "in", "the", "order", "they", "appear", "in", "the", "record", "." ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/record.rb#L177-L197
train
riboseinc/ribose-ruby
lib/ribose/file_uploader.rb
Ribose.FileUploader.create
def create upload_meta = prepare_to_upload response = upload_to_aws_s3(upload_meta) notify_ribose_file_upload_endpoint(response, upload_meta.fields.key) end
ruby
def create upload_meta = prepare_to_upload response = upload_to_aws_s3(upload_meta) notify_ribose_file_upload_endpoint(response, upload_meta.fields.key) end
[ "def", "create", "upload_meta", "=", "prepare_to_upload", "response", "=", "upload_to_aws_s3", "(", "upload_meta", ")", "notify_ribose_file_upload_endpoint", "(", "response", ",", "upload_meta", ".", "fields", ".", "key", ")", "end" ]
Initialize the file uploader @param space_id [String] The Space UUID @param file [File] The complete path for file @param attributes [Hash] Attributes as a Hash Create a file upload @return [Sawyer::Resource] File upload response.
[ "Initialize", "the", "file", "uploader" ]
3f6ef9060876d17b3c0efd3f0cefdfe3841cece9
https://github.com/riboseinc/ribose-ruby/blob/3f6ef9060876d17b3c0efd3f0cefdfe3841cece9/lib/ribose/file_uploader.rb#L21-L25
train
riboseinc/ribose-ruby
lib/ribose/request.rb
Ribose.Request.request
def request(options = {}) parsable = extract_config_option(:parse) != false options[:query] = extract_config_option(:query) || {} response = agent.call(http_method, api_endpoint, data, options) parsable == true ? response.data : response end
ruby
def request(options = {}) parsable = extract_config_option(:parse) != false options[:query] = extract_config_option(:query) || {} response = agent.call(http_method, api_endpoint, data, options) parsable == true ? response.data : response end
[ "def", "request", "(", "options", "=", "{", "}", ")", "parsable", "=", "extract_config_option", "(", ":parse", ")", "!=", "false", "options", "[", ":query", "]", "=", "extract_config_option", "(", ":query", ")", "||", "{", "}", "response", "=", "agent", ".", "call", "(", "http_method", ",", "api_endpoint", ",", "data", ",", "options", ")", "parsable", "==", "true", "?", "response", ".", "data", ":", "response", "end" ]
Initialize a Request @param http_method [Symbol] HTTP verb as sysmbol @param endpoint [String] The relative API endpoint @param data [Hash] Attributes / Options as a Hash @return [Ribose::Request] Make a HTTP Request @param options [Hash] Additonal options hash @return [Sawyer::Resource]
[ "Initialize", "a", "Request" ]
3f6ef9060876d17b3c0efd3f0cefdfe3841cece9
https://github.com/riboseinc/ribose-ruby/blob/3f6ef9060876d17b3c0efd3f0cefdfe3841cece9/lib/ribose/request.rb#L22-L28
train
ruby-marc/ruby-marc
lib/marc/datafield.rb
MARC.DataField.to_hash
def to_hash field_hash = {@tag=>{'ind1'=>@indicator1,'ind2'=>@indicator2,'subfields'=>[]}} self.each do |subfield| field_hash[@tag]['subfields'] << {subfield.code=>subfield.value} end field_hash end
ruby
def to_hash field_hash = {@tag=>{'ind1'=>@indicator1,'ind2'=>@indicator2,'subfields'=>[]}} self.each do |subfield| field_hash[@tag]['subfields'] << {subfield.code=>subfield.value} end field_hash end
[ "def", "to_hash", "field_hash", "=", "{", "@tag", "=>", "{", "'ind1'", "=>", "@indicator1", ",", "'ind2'", "=>", "@indicator2", ",", "'subfields'", "=>", "[", "]", "}", "}", "self", ".", "each", "do", "|", "subfield", "|", "field_hash", "[", "@tag", "]", "[", "'subfields'", "]", "<<", "{", "subfield", ".", "code", "=>", "subfield", ".", "value", "}", "end", "field_hash", "end" ]
Turn the variable field and subfields into a hash for MARC-in-JSON
[ "Turn", "the", "variable", "field", "and", "subfields", "into", "a", "hash", "for", "MARC", "-", "in", "-", "JSON" ]
5b06242c2a4eb5d5ce1665713181debed94ed8a0
https://github.com/ruby-marc/ruby-marc/blob/5b06242c2a4eb5d5ce1665713181debed94ed8a0/lib/marc/datafield.rb#L111-L117
train
chatterbugapp/cacheql
lib/cacheql/resolve_wrapper.rb
CacheQL.ResolveWrapper.call
def call(obj, args, ctx) cache_key = [CacheQL::Railtie.config.global_key, obj.cache_key, ctx.field.name] CacheQL::Railtie.config.cache.fetch(cache_key, expires_in: CacheQL::Railtie.config.expires_range.sample.minutes) do @resolver_func.call(obj, args, ctx) end end
ruby
def call(obj, args, ctx) cache_key = [CacheQL::Railtie.config.global_key, obj.cache_key, ctx.field.name] CacheQL::Railtie.config.cache.fetch(cache_key, expires_in: CacheQL::Railtie.config.expires_range.sample.minutes) do @resolver_func.call(obj, args, ctx) end end
[ "def", "call", "(", "obj", ",", "args", ",", "ctx", ")", "cache_key", "=", "[", "CacheQL", "::", "Railtie", ".", "config", ".", "global_key", ",", "obj", ".", "cache_key", ",", "ctx", ".", "field", ".", "name", "]", "CacheQL", "::", "Railtie", ".", "config", ".", "cache", ".", "fetch", "(", "cache_key", ",", "expires_in", ":", "CacheQL", "::", "Railtie", ".", "config", ".", "expires_range", ".", "sample", ".", "minutes", ")", "do", "@resolver_func", ".", "call", "(", "obj", ",", "args", ",", "ctx", ")", "end", "end" ]
Resolve function level caching!
[ "Resolve", "function", "level", "caching!" ]
c22f56292e18e11d2483a9afca38bae31b7d7535
https://github.com/chatterbugapp/cacheql/blob/c22f56292e18e11d2483a9afca38bae31b7d7535/lib/cacheql/resolve_wrapper.rb#L12-L18
train
solnic/transflow
lib/transflow/transaction.rb
Transflow.Transaction.call
def call(input, options = {}) handler = handler_steps(options).map(&method(:step)).reduce(:>>) handler.call(input) rescue StepError => err raise TransactionFailedError.new(self, err) end
ruby
def call(input, options = {}) handler = handler_steps(options).map(&method(:step)).reduce(:>>) handler.call(input) rescue StepError => err raise TransactionFailedError.new(self, err) end
[ "def", "call", "(", "input", ",", "options", "=", "{", "}", ")", "handler", "=", "handler_steps", "(", "options", ")", ".", "map", "(", "&", "method", "(", ":step", ")", ")", ".", "reduce", "(", ":>>", ")", "handler", ".", "call", "(", "input", ")", "rescue", "StepError", "=>", "err", "raise", "TransactionFailedError", ".", "new", "(", "self", ",", "err", ")", "end" ]
Call the transaction Once transaction is called it will call the first step and its result will be passed to the second step and so on. @example my_container = { add_one: -> i { i + 1 }, add_two: -> j { j + 2 } } transaction = Transflow(container: my_container) { step(:one, with: :add_one) { step(:two, with: :add_two) } } transaction.call(1) # 4 @param [Object] input The input for the first step @param [Hash] options The curry-args map, optional @return [Object] @raises TransactionFailedError @api public
[ "Call", "the", "transaction" ]
725eaa8e24f6077b07d7c4c47ddab1d78ceb5577
https://github.com/solnic/transflow/blob/725eaa8e24f6077b07d7c4c47ddab1d78ceb5577/lib/transflow/transaction.rb#L107-L112
train
muffinista/namey
lib/namey/parser.rb
Namey.Parser.create_table
def create_table(name) if ! db.tables.include?(name.to_sym) db.create_table name do String :name, :size => 15 Float :freq index :freq end end end
ruby
def create_table(name) if ! db.tables.include?(name.to_sym) db.create_table name do String :name, :size => 15 Float :freq index :freq end end end
[ "def", "create_table", "(", "name", ")", "if", "!", "db", ".", "tables", ".", "include?", "(", "name", ".", "to_sym", ")", "db", ".", "create_table", "name", "do", "String", ":name", ",", ":size", "=>", "15", "Float", ":freq", "index", ":freq", "end", "end", "end" ]
create a name table
[ "create", "a", "name", "table" ]
10e62cba0bab2603f95ad454f752c1dc93685461
https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/parser.rb#L95-L103
train
muffinista/namey
lib/namey/parser.rb
Namey.Parser.cleanup_surname
def cleanup_surname(name) if name.length > 4 name.gsub!(/^Mc(\w+)/) { |s| "Mc#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Osh(\w+)/) { |s| "O'sh#{$1}" } name.gsub!(/^Van(\w+)/) { |s| "Van#{$1.capitalize}" } name.gsub!(/^Von(\w+)/) { |s| "Von#{$1.capitalize}" } # name.gsub!(/^Dev(\w+)/) { |s| "DeV#{$1}" } end name end
ruby
def cleanup_surname(name) if name.length > 4 name.gsub!(/^Mc(\w+)/) { |s| "Mc#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Mac(\w+)/) { |s| "Mac#{$1.capitalize}" } name.gsub!(/^Osh(\w+)/) { |s| "O'sh#{$1}" } name.gsub!(/^Van(\w+)/) { |s| "Van#{$1.capitalize}" } name.gsub!(/^Von(\w+)/) { |s| "Von#{$1.capitalize}" } # name.gsub!(/^Dev(\w+)/) { |s| "DeV#{$1}" } end name end
[ "def", "cleanup_surname", "(", "name", ")", "if", "name", ".", "length", ">", "4", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Mc#{$1.capitalize}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Mac#{$1.capitalize}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Mac#{$1.capitalize}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"O'sh#{$1}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Van#{$1.capitalize}\"", "}", "name", ".", "gsub!", "(", "/", "\\w", "/", ")", "{", "|", "s", "|", "\"Von#{$1.capitalize}\"", "}", "end", "name", "end" ]
apply some simple regexps to clean up surnames
[ "apply", "some", "simple", "regexps", "to", "clean", "up", "surnames" ]
10e62cba0bab2603f95ad454f752c1dc93685461
https://github.com/muffinista/namey/blob/10e62cba0bab2603f95ad454f752c1dc93685461/lib/namey/parser.rb#L115-L126
train
postmodern/hexdump
lib/hexdump/dumper.rb
Hexdump.Dumper.each_word
def each_word(data,&block) return enum_for(:each_word,data) unless block unless data.respond_to?(:each_byte) raise(ArgumentError,"the data to hexdump must define #each_byte") end if @word_size > 1 word = 0 count = 0 init_shift = if @endian == :big ((@word_size - 1) * 8) else 0 end shift = init_shift data.each_byte do |b| word |= (b << shift) if @endian == :big shift -= 8 else shift += 8 end count += 1 if count >= @word_size yield word word = 0 count = 0 shift = init_shift end end # yield the remaining word yield word if count > 0 else data.each_byte(&block) end end
ruby
def each_word(data,&block) return enum_for(:each_word,data) unless block unless data.respond_to?(:each_byte) raise(ArgumentError,"the data to hexdump must define #each_byte") end if @word_size > 1 word = 0 count = 0 init_shift = if @endian == :big ((@word_size - 1) * 8) else 0 end shift = init_shift data.each_byte do |b| word |= (b << shift) if @endian == :big shift -= 8 else shift += 8 end count += 1 if count >= @word_size yield word word = 0 count = 0 shift = init_shift end end # yield the remaining word yield word if count > 0 else data.each_byte(&block) end end
[ "def", "each_word", "(", "data", ",", "&", "block", ")", "return", "enum_for", "(", ":each_word", ",", "data", ")", "unless", "block", "unless", "data", ".", "respond_to?", "(", ":each_byte", ")", "raise", "(", "ArgumentError", ",", "\"the data to hexdump must define #each_byte\"", ")", "end", "if", "@word_size", ">", "1", "word", "=", "0", "count", "=", "0", "init_shift", "=", "if", "@endian", "==", ":big", "(", "(", "@word_size", "-", "1", ")", "*", "8", ")", "else", "0", "end", "shift", "=", "init_shift", "data", ".", "each_byte", "do", "|", "b", "|", "word", "|=", "(", "b", "<<", "shift", ")", "if", "@endian", "==", ":big", "shift", "-=", "8", "else", "shift", "+=", "8", "end", "count", "+=", "1", "if", "count", ">=", "@word_size", "yield", "word", "word", "=", "0", "count", "=", "0", "shift", "=", "init_shift", "end", "end", "yield", "word", "if", "count", ">", "0", "else", "data", ".", "each_byte", "(", "&", "block", ")", "end", "end" ]
Creates a new Hexdump dumper. @param [Hash] options Additional options. @option options [Integer] :width (16) The number of bytes to dump for each line. @option options [Integer] :endian (:little) The endianness that the bytes are organized in. Supported endianness include `:little` and `:big`. @option options [Integer] :word_size (1) The number of bytes within a word. @option options [Symbol, Integer] :base (:hexadecimal) The base to print bytes in. Supported bases include, `:hexadecimal`, `:hex`, `16, `:decimal`, `:dec`, `10, `:octal`, `:oct`, `8`, `:binary`, `:bin` and `2`. @option options [Boolean] :ascii (false) Print ascii characters when possible. @raise [ArgumentError] The values for `:base` or `:endian` were unknown. @since 0.2.0 Iterates over every word within the data. @param [#each_byte] data The data containing bytes. @yield [word] The given block will be passed each word within the data. @yieldparam [Integer] An unpacked word from the data. @return [Enumerator] If no block is given, an Enumerator will be returned. @raise [ArgumentError] The given data does not define the `#each_byte` method. @since 0.2.0
[ "Creates", "a", "new", "Hexdump", "dumper", "." ]
e9138798b7e23ca2b9588cc3b254bd54fc334edf
https://github.com/postmodern/hexdump/blob/e9138798b7e23ca2b9588cc3b254bd54fc334edf/lib/hexdump/dumper.rb#L244-L287
train
postmodern/hexdump
lib/hexdump/dumper.rb
Hexdump.Dumper.each
def each(data) return enum_for(:each,data) unless block_given? index = 0 count = 0 numeric = [] printable = [] each_word(data) do |word| numeric << format_numeric(word) printable << format_printable(word) count += 1 if count >= @width yield index, numeric, printable numeric.clear printable.clear index += (@width * @word_size) count = 0 end end if count > 0 # yield the remaining data yield index, numeric, printable end end
ruby
def each(data) return enum_for(:each,data) unless block_given? index = 0 count = 0 numeric = [] printable = [] each_word(data) do |word| numeric << format_numeric(word) printable << format_printable(word) count += 1 if count >= @width yield index, numeric, printable numeric.clear printable.clear index += (@width * @word_size) count = 0 end end if count > 0 # yield the remaining data yield index, numeric, printable end end
[ "def", "each", "(", "data", ")", "return", "enum_for", "(", ":each", ",", "data", ")", "unless", "block_given?", "index", "=", "0", "count", "=", "0", "numeric", "=", "[", "]", "printable", "=", "[", "]", "each_word", "(", "data", ")", "do", "|", "word", "|", "numeric", "<<", "format_numeric", "(", "word", ")", "printable", "<<", "format_printable", "(", "word", ")", "count", "+=", "1", "if", "count", ">=", "@width", "yield", "index", ",", "numeric", ",", "printable", "numeric", ".", "clear", "printable", ".", "clear", "index", "+=", "(", "@width", "*", "@word_size", ")", "count", "=", "0", "end", "end", "if", "count", ">", "0", "yield", "index", ",", "numeric", ",", "printable", "end", "end" ]
Iterates over the hexdump. @param [#each_byte] data The data to be hexdumped. @yield [index,numeric,printable] The given block will be passed the hexdump break-down of each segment. @yieldparam [Integer] index The index of the hexdumped segment. @yieldparam [Array<String>] numeric The numeric representation of the segment. @yieldparam [Array<String>] printable The printable representation of the segment. @return [Enumerator] If no block is given, an Enumerator will be returned. @since 0.2.0
[ "Iterates", "over", "the", "hexdump", "." ]
e9138798b7e23ca2b9588cc3b254bd54fc334edf
https://github.com/postmodern/hexdump/blob/e9138798b7e23ca2b9588cc3b254bd54fc334edf/lib/hexdump/dumper.rb#L313-L343
train
postmodern/hexdump
lib/hexdump/dumper.rb
Hexdump.Dumper.dump
def dump(data,output=$stdout) unless output.respond_to?(:<<) raise(ArgumentError,"output must support the #<< method") end bytes_segment_width = ((@width * @format_width) + @width) line_format = "%.8x %-#{bytes_segment_width}s |%s|\n" index = 0 count = 0 numeric = '' printable = '' each_word(data) do |word| numeric << format_numeric(word) << ' ' printable << format_printable(word) count += 1 if count >= @width output << sprintf(line_format,index,numeric,printable) numeric = '' printable = '' index += (@width * @word_size) count = 0 end end if count > 0 # output the remaining line output << sprintf(line_format,index,numeric,printable) end end
ruby
def dump(data,output=$stdout) unless output.respond_to?(:<<) raise(ArgumentError,"output must support the #<< method") end bytes_segment_width = ((@width * @format_width) + @width) line_format = "%.8x %-#{bytes_segment_width}s |%s|\n" index = 0 count = 0 numeric = '' printable = '' each_word(data) do |word| numeric << format_numeric(word) << ' ' printable << format_printable(word) count += 1 if count >= @width output << sprintf(line_format,index,numeric,printable) numeric = '' printable = '' index += (@width * @word_size) count = 0 end end if count > 0 # output the remaining line output << sprintf(line_format,index,numeric,printable) end end
[ "def", "dump", "(", "data", ",", "output", "=", "$stdout", ")", "unless", "output", ".", "respond_to?", "(", ":<<", ")", "raise", "(", "ArgumentError", ",", "\"output must support the #<< method\"", ")", "end", "bytes_segment_width", "=", "(", "(", "@width", "*", "@format_width", ")", "+", "@width", ")", "line_format", "=", "\"%.8x %-#{bytes_segment_width}s |%s|\\n\"", "index", "=", "0", "count", "=", "0", "numeric", "=", "''", "printable", "=", "''", "each_word", "(", "data", ")", "do", "|", "word", "|", "numeric", "<<", "format_numeric", "(", "word", ")", "<<", "' '", "printable", "<<", "format_printable", "(", "word", ")", "count", "+=", "1", "if", "count", ">=", "@width", "output", "<<", "sprintf", "(", "line_format", ",", "index", ",", "numeric", ",", "printable", ")", "numeric", "=", "''", "printable", "=", "''", "index", "+=", "(", "@width", "*", "@word_size", ")", "count", "=", "0", "end", "end", "if", "count", ">", "0", "output", "<<", "sprintf", "(", "line_format", ",", "index", ",", "numeric", ",", "printable", ")", "end", "end" ]
Dumps the hexdump. @param [#each_byte] data The data to be hexdumped. @param [#<<] output The output to dump the hexdump to. @return [nil] @raise [ArgumentError] The output value does not support the `#<<` method. @since 0.2.0
[ "Dumps", "the", "hexdump", "." ]
e9138798b7e23ca2b9588cc3b254bd54fc334edf
https://github.com/postmodern/hexdump/blob/e9138798b7e23ca2b9588cc3b254bd54fc334edf/lib/hexdump/dumper.rb#L361-L396
train
postmodern/hexdump
lib/hexdump/dumper.rb
Hexdump.Dumper.format_printable
def format_printable(word) if @word_size == 1 PRINTABLE[word] elsif (RUBY_VERSION > '1.9.' && (word >= -2 && word <= 0x7fffffff)) begin word.chr(Encoding::UTF_8) rescue RangeError UNPRINTABLE end else UNPRINTABLE end end
ruby
def format_printable(word) if @word_size == 1 PRINTABLE[word] elsif (RUBY_VERSION > '1.9.' && (word >= -2 && word <= 0x7fffffff)) begin word.chr(Encoding::UTF_8) rescue RangeError UNPRINTABLE end else UNPRINTABLE end end
[ "def", "format_printable", "(", "word", ")", "if", "@word_size", "==", "1", "PRINTABLE", "[", "word", "]", "elsif", "(", "RUBY_VERSION", ">", "'1.9.'", "&&", "(", "word", ">=", "-", "2", "&&", "word", "<=", "0x7fffffff", ")", ")", "begin", "word", ".", "chr", "(", "Encoding", "::", "UTF_8", ")", "rescue", "RangeError", "UNPRINTABLE", "end", "else", "UNPRINTABLE", "end", "end" ]
Converts a word into a printable String. @param [Integer] word The word to convert. @return [String] The printable representation of the word. @since 0.2.0
[ "Converts", "a", "word", "into", "a", "printable", "String", "." ]
e9138798b7e23ca2b9588cc3b254bd54fc334edf
https://github.com/postmodern/hexdump/blob/e9138798b7e23ca2b9588cc3b254bd54fc334edf/lib/hexdump/dumper.rb#L434-L446
train