repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
ploch/rbot
plugins/mlb.rb
# mlb # by <NAME> <<EMAIL>> 2007-01-23 # # display mlb scores require 'uri/common' require 'yaml' require 'tzinfo' require '0lib_rbot' class MlbPlugin < Plugin include PluginLib def initialize super @mymlb = "mymlb => get results for your teams, mymlb [clear] [ team [team...] ] => save your fav teams" end def help(plugin, topic="") "mlb => get last nights results, mlb <team> => get results of last game for <team> " + @mymlb end # get latest results for a specific team def mlb_team(m, params) info = YahooSports::MLB.get_team_stats(params[:team]) last_game = info.last5[-1] game_date = last_game.date.strftime('%a %b %d') ret = sprintf("%s (%s, %s): %s, %s%s - %s", info.name, info.standing, info.position, game_date, (last_game.away ? "at " : ""), last_game.team, last_game.status) return m.reply(ret) end def mymlb(m, params) if not @registry.has_key?(m.sourceaddress) m.reply "you need to setup your favs! " + @mymlb return end teams = @registry[m.sourceaddress] if teams.empty? then m.reply "you need to setup your favs! " + @mymlb return end params = Hash.new teams.each { |t| params[:team] = t mlb_team(m, params) } end def set_default(m, params) teams = params[:teams] if @registry.has_key?(m.sourceaddress) then saved_teams = @registry[m.sourceaddress] else saved_teams = Array.new end if teams[0] == 'clear' then saved_teams.clear @registry[m.sourceaddress] = saved_teams m.reply 'done' return elsif teams[0] == 'list' then m.reply 'current teams: ' + saved_teams.join(' ') return end saved_teams.clear teams.each { |t| (team, html) = get_team(t) saved_teams.push(t) unless team.nil? } @registry[m.sourceaddress] = saved_teams m.reply 'saved' end def mlb_live(m, params) games = YahooSports::MLB.get_homepage_games('live') date = Time.parse(eastern_time().strftime('%Y%m%d')) show_games(m, games, date, "Live game(s): ", params[:team]) end def mlb_today(m, params) games = YahooSports::MLB.get_homepage_games() date = Time.parse(eastern_time().strftime('%Y%m%d')) show_games(m, games, date, "Today's game(s): ") end def mlb_yesterday(m, params) games = YahooSports::MLB.get_homepage_games() date = Time.parse(eastern_time().strftime('%Y%m%d')) - 86400 show_games(m, games, date, "Yesterday's game(s): ") end def show_games(m, games, date, text, team = '') scores = [] games.each { |game| next if not team.nil? and not team.empty? and not (game.team1.downcase.include? team or game.team2.downcase.include? team) next if Time.parse(game.date.strftime('%Y%m%d')) != date if game.state == 'preview' then game.status = sprintf("%s, %s", game.status, game.extra) if game.extra scores << sprintf("%s at %s (%s, %s)", game.team1, game.team2, game.state, game.status) next end if game.state == 'final' then if game.score1.to_i > game.score2.to_i then game.team1 += '*' else game.team2 += '*' end game.status = 'F' else # live game.status = sprintf('%s, %s', game.state, game.status) end scores << sprintf("%s %s at %s %s (%s)", game.team1, game.score1, game.team2, game.score2, game.status.strip) } return m.reply(text + 'none') if scores.empty? m.reply(text + scores.join(' / ')) end end plugin = MlbPlugin.new plugin.map 'mlb live [:team]', :action => 'mlb_live' plugin.map 'mlb now [:team]', :action => 'mlb_live' plugin.map 'mlb today', :action => 'mlb_today' plugin.map 'mlb yest', :action => 'mlb_yesterday' plugin.map 'mlb yesterday', :action => 'mlb_yesterday' plugin.map 'mlb', :action => 'mlb_yesterday' plugin.map 'mlb :team', :action => 'mlb_team' plugin.map 'mymlb', :action => 'mymlb' plugin.map 'mymlb *teams', :action => 'set_default'
ploch/rbot
plugins/test/plugin_test.rb
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/plugin_stub' plugin = load_plugin("tiny_weather") plugin.do_tiny_weather(Msg.new, { :zip => 11375 })
ploch/rbot
plugins/nfl.rb
<filename>plugins/nfl.rb # nfl # by <NAME> <<EMAIL>> 2008-09-23 # # display nfl scores require 'uri/common' require 'yaml' require 'tzinfo' require '0lib_rbot' class NflPlugin < Plugin include PluginLib def initialize super @mynfl = "mynfl => get results for your teams, mynfl [clear] [ team [team...] ] => save your fav teams" end def help(plugin, topic="") "nfl => get last nights results, nfl <team> => get results of last game for <team> " + @mynfl end # get latest results for a specific team def nfl_team(m, params) params[:teams].each { |team| info = YahooSports::NFL.get_team_stats(team) last_game = info.last5[-1] game_date = last_game.date.strftime('%a %b %d') ret = sprintf("%s (%s, %s): %s, %s%s - %s", info.name, info.standing, info.position, game_date, (last_game.away ? "at " : ""), last_game.team, last_game.status) m.reply(ret) } end def mynfl(m, params) if not @registry.has_key?(m.sourceaddress) m.reply "you need to setup your favs! " + @mynfl return end teams = @registry[m.sourceaddress] if teams.empty? then m.reply "you need to setup your favs! " + @mynfl return end params = Hash.new teams.each { |t| params[:team] = t nfl_team(m, params) } end def set_default(m, params) teams = params[:teams] if @registry.has_key?(m.sourceaddress) then saved_teams = @registry[m.sourceaddress] else saved_teams = Array.new end if teams[0] == 'clear' then saved_teams.clear @registry[m.sourceaddress] = saved_teams m.reply 'done' return elsif teams[0] == 'list' then m.reply 'current teams: ' + saved_teams.join(' ') return end saved_teams.clear teams.each { |t| (team, html) = get_team(t) saved_teams.push(t) unless team.nil? } @registry[m.sourceaddress] = saved_teams m.reply 'saved' end def nfl_live(m, params) games = YahooSports::NFL.get_homepage_games('live') date = Time.parse(eastern_time().strftime('%Y%m%d')) show_games(m, games, date, "Live game(s): ", params[:team]) end def nfl_today(m, params) games = YahooSports::NFL.get_homepage_games() date = Time.parse(eastern_time().strftime('%Y%m%d')) show_games(m, games, date, "Today's game(s): ") end def nfl_yesterday(m, params) games = YahooSports::NFL.get_homepage_games() date = Time.parse(eastern_time().strftime('%Y%m%d')) - 86400 show_games(m, games, date, "Yesterday's game(s): ") end def show_games(m, games, date, text, team = '') scores = [] games.each { |game| next if not team.nil? and not team.empty? and not (game.team1.downcase.include? team or game.team2.downcase.include? team) next if Time.parse(game.date.strftime('%Y%m%d')) != date if game.state == 'preview' then game.status = sprintf("%s, %s", game.status, game.extra) if game.extra scores << sprintf("%s at %s (%s, %s)", game.team1, game.team2, game.state, game.status) next end if game.state == 'final' then if game.score1.to_i > game.score2.to_i then game.team1 += '*' else game.team2 += '*' end game.status = 'F' else # live game.status = sprintf('%s, %s', game.state, game.status) end scores << sprintf("%s %s at %s %s (%s)", game.team1, game.score1, game.team2, game.score2, game.status.strip) } return m.reply(text + 'none') if scores.empty? m.reply(text + scores.join(' / ')) end end plugin = NflPlugin.new plugin.map 'nfl live [:team]', :action => 'nfl_live' plugin.map 'nfl now [:team]', :action => 'nfl_live' plugin.map 'nfl today', :action => 'nfl_today' plugin.map 'nfl yest', :action => 'nfl_yesterday' plugin.map 'nfl yesterday', :action => 'nfl_yesterday' plugin.map 'nfl', :action => 'nfl_yesterday' plugin.map 'nfl *teams', :action => 'nfl_team' plugin.map 'mynfl', :action => 'mynfl' plugin.map 'mynfl *teams', :action => 'set_default'
ploch/rbot
plugins/debt.rb
# we gots debt and lots of it! # by <NAME> <<EMAIL>> 2008-10-09 # # lookup the national debt require 'rubygems' require 'scrapi' class DebtPlugin < Plugin include PluginLib def help(plugin, topic="") return "debt => get current national debt" end def do_debt(m,params) debt = get_national_debt() m.reply "unable to get current national debt" if not debt m.reply sprintf("Current National Debt: $%s", debt) end def get_national_debt() national_debt = Scraper.define do process "table.data1 td:nth-child(4)", :debt => :text result :debt end html = fetchurl('http://www.treasurydirect.gov/NP/BPDLogin?application=np') debt = national_debt.scrape(html) return debt end end plugin = DebtPlugin.new plugin.map 'debt', :action => 'do_debt'
ploch/rbot
plugins/nhl.rb
<reponame>ploch/rbot<gh_stars>1-10 # nhl # by <NAME> <<EMAIL>> 2007-01-23 # # display nhl scores require 'yahoo_sports' require '0lib_rbot' class NhlPlugin < Plugin include PluginLib def help(plugin, topic="") "nhl => get last nights results, nhl <team> => get results of last game for <team>" end # get latest results for a specific team def nhl_team(m, params) info = YahooSports::NHL.get_team_stats(params[:team]) last_game = info.last5[-1] game_date = last_game.date.strftime('%a %b %d') ret = sprintf("%s (%s, %s): %s, %s%s - %s", info.name, info.standing, info.position, game_date, (last_game.away ? "at " : ""), last_game.team, last_game.status) return m.reply(ret) end def nhl_live(m, params) games = YahooSports::NHL.get_homepage_games('live') date = Time.parse(eastern_time().strftime('%Y%m%d')) show_games(m, games, date, "Live games: ") end def nhl_today(m, params) games = YahooSports::NHL.get_homepage_games() date = Time.parse(eastern_time().strftime('%Y%m%d')) show_games(m, games, date, "Today's games: ") end def nhl_yesterday(m, params) games = YahooSports::NHL.get_homepage_games() date = Time.parse(eastern_time().strftime('%Y%m%d')) - 86400 show_games(m, games, date, "Yesterday's games: ") end def show_games(m, games, date, text, team = '') scores = [] games.each { |game| next if not team.nil? and not team.empty? and not (game.team1.downcase.include? team or game.team2.downcase.include? team) next if Time.parse(game.date.strftime('%Y%m%d')) != date if game.state == 'preview' then game.status = sprintf("%s, %s", game.status, game.extra) if game.extra scores << sprintf("%s at %s (%s, %s)", game.team1, game.team2, game.state, game.status) next end if game.state == 'final' then if game.score1.to_i > game.score2.to_i then game.team1 += '*' else game.team2 += '*' end game.status = 'F' else # live game.status = sprintf('%s, %s', game.state, game.status) end scores << sprintf("%s %s at %s %s (%s)", game.team1, game.score1, game.team2, game.score2, game.status.strip) } return m.reply(text + 'none') if scores.empty? m.reply(text + scores.join(' / ')) end end plugin = NhlPlugin.new plugin.map 'nhl live', :action => 'nhl_live' plugin.map 'nhl now', :action => 'nhl_live' plugin.map 'nhl today', :action => 'nhl_today' plugin.map 'nhl yest', :action => 'nhl_yesterday' plugin.map 'nhl yesterday', :action => 'nhl_yesterday' plugin.map 'nhl', :action => 'nhl_yesterday' plugin.map 'nhl :team', :action => 'nhl_team'
ploch/rbot
plugins/fmylife.rb
<gh_stars>1-10 # fmylife! # by <NAME> <<EMAIL>> 2009-03-20 # # scrape from fmylife.com require 'rubygems' require 'scrapi' require '0lib_rbot' class FMyLifePlugin < Plugin include PluginLib def initialize super @url = 'http://www.fmylife.com/' end def help(plugin, topic="") return "fml => get random entry from fmylife.com" end def do_fml(m, params) if params[:num] then num = params[:num].gsub('#', '') url = @url + num else url = @url + 'random' end posts = scrape_fml(url) return m.reply "error getting posts from fmylife.com" if not posts posts = posts.sort_by { rand } p = posts[0] m.reply sprintf("%s: %s", p.num, p.text) end def scrape_fml(url) html = fetchurl(url) fml_post = Scraper.define do process_first "p", :text => :text process_first "div.date a", :num => :text result :num, :text end fml_posts = Scraper.define do array :posts process "div.post", :posts => fml_post result :posts end posts = fml_posts.scrape(html) posts.delete_if { |p| p.num.nil? } posts.each { |p| strip_tags(p.text) } return posts end end plugin = FMyLifePlugin.new plugin.map 'fml [:num]', :action => 'do_fml'
ploch/rbot
plugins/stocks.rb
<reponame>ploch/rbot # stocks # by <NAME> <brian -at- ploch.net> # by <NAME> <<EMAIL>> 2007-01-23 # # stock lookup. # # initial lookup by ploch. symbol lookup added by chetan. also the eliteness. require 'rubygems' require 'yahoofinance' require 'json' require '0lib_rbot' class StocksPlugin < Plugin include PluginLib def initialize super @google_url = 'http://finance.google.com/finance/match?matchtype=matchall&q=' # map of month => code for futures @futures_code = { 1 => "F", 2 => "G", 3 => "H", 4 => "J", 5 => "K", 6 => "M", 7 => "N", 8 => "Q", 9 => "U", 10 => "V", 11 => "X", 12 => "Z" } # '<Symbol> <Market>' @stocks = { 'gold' => 'GC CMX', 'copper' => 'HG CMX', 'silver' => 'SI CMX', 'oil' => 'CL NYM', 'corn' => 'C CBT', 'oats' => 'O CBT', 'n gas' => 'NG NYM', 'rbob' => 'RB NYM' } end def help(plugin, topic="") return "stocks symbol1 symbol2 ..." end def do_emea(m, params) params[:symbols] = [ '^N225', '^HSI', '^FTSE', '^GDAXI' ] return do_lookup(m,params) end # futures symbols # http://finance.yahoo.com/futures? # def do_oil(m, params) oil_symbol = get_commodity_code "oil" params[:symbols] = [ oil_symbol ] return do_lookup(m,params) end def get_commodity_code(stock) stock_data = @stocks[stock].split date = Time.new year = date.year.to_s[-2,2] if stock_data[1] == "NYM" then # Nymex only trades futures month=date.month + 1 else month=date.month end future_code = @futures_code[month] stock_symbol = "#{stock_data[0]}#{future_code}#{year}.#{stock_data[1]}" end def do_stocks3(m, params) list = "" @stocks.each do |x| code = get_commodity_code x[0] list += code + " " end params[:symbols] = list.split return do_lookup(m,params) end def do_lookup(m,params) if params[:symbols].length == 0 then # no sybmols passed, lookup major indexes params[:symbols].push( '^DJI', '^IXIC', '^GSPC' ) end s = params[:symbols].join(" ") if s =~ /^['"].*['"]$/ then # surrounded in quotes, do a symbol lookup using google s = s[1..-2] begin symbols = symbol_lookup(s) rescue return m.reply($!) end else # pass comma separated list of symbols symbols = params[:symbols].join(",") end _lookup(m, symbols) end def _lookup(m, symbol) responses = get_quotes(symbol) if responses.empty? then begin responses = get_quotes(symbol_lookup(symbol)) return m.reply( sprintf("no data found for '%s'", symbol) ) rescue debug "dying.... %!" return m.reply($!) end end responses.each do |r| m.reply r end end def get_quotes(symbols) responses = [] YahooFinance::get_standard_quotes( symbols ).each do |symbol, qt| if valid_quote(qt) r = "#{qt.name} (#{symbol}) -> #{qt.lastTrade} Change: #{qt.change} Low: #{qt.dayLow} High: #{qt.dayHigh}" r += " Volume: #{qt.volume} " if qt.volume > 0 responses << r end end return responses end # returns false if all of these values are 0: # averageDailyVolume, bid, ask, lastTrade, and volume def valid_quote(q) if q.averageDailyVolume == 0 and q.ask == 0 and q.bid == 0 and q.lastTrade == 0 and q.volume == 0 then return false end return true end def symbol_lookup(str) json_response = fetchurl(sprintf('%s%s', @google_url, str)) if not json_response then raise sprintf('Lookup failed for "%s"', str) end sugg = JSON.parse(json_response) if sugg['matches'].nil? or sugg['matches'].empty? then raise sprintf('No symbols found for "%s"', str) end matches = sugg['matches'].first['t'] end end # GOOG -> 457.37 -4.52 / Last Trade N/A / Change -0.98% / Min 457.24 / Max 457.37 plugin = StocksPlugin.new plugin.map 'stocks [*symbols]', :action => 'do_lookup', :defaults => { :symbols => nil } plugin.map 'stocks2', :action => 'do_emea' plugin.map 'stocks3', :action => 'do_stocks3' plugin.map 'oil', :action => 'do_oil'
ploch/rbot
plugins/tiny_weather.rb
# tiny weather script # by <NAME> <<EMAIL>> 2009-03-20 # # scrapes weather.com require 'rubygems' require 'scrapi' require '0lib_rbot' class TinyWeatherPlugin < Plugin include PluginLib def initialize super end def help(plugin, topic="") return "tw [zip] => get hourly forecast from weather.com; tw default <zip> => set your default zipcode" end # Massillon, OH (44647) 11 am: 63F (10%) 1 pm: 72F (10%) 3 pm: 76F (10%) 5 pm: 75F (10%) no rain :) def do_tiny_weather(m, params) zip = check_zip(m, params) return if zip.nil? w = nil begin w = scrape_hourly_weather(zip) rescue => ex end return m.reply("error getting hourly weather") if not w s = [w.location] i = 0 precip = 0 w.hours.each { |h| i += 1 precip = h.precip.to_i if h.precip.to_i > precip next if i % 2 == 0 s << sprintf("%s: %s (%s)", h.hour, h.temp, h.precip) } if precip < 30 then s << "no rain :)" elsif precip == 30 or precip == 40 then s << "might want that umbrella" else s << "grab an umbrella!" end m.reply(s.join(' ')) end # Massillon, OH (44647) 11 am: 63F (10%) 1 pm: 72F (10%) 3 pm: 76F (10%) 5 pm: 75F (10%) no rain :) # Massillon, OH (44647) Sat: 86F (40%) Sun: 80F (10%) Mon: 79F (0%) Tue: 80F (10%) Wed: 83F (30%) Thu: 81F (60%) def do_tiny_weather_forecast(m, params) zip = check_zip(m, params) return if zip.nil? do_tiny_weather(m, params) # do this first w = nil begin w = scrape_weather_forecast(zip) rescue => ex end return m.reply("error getting weather forecast") if not w s = [ w.location ] date = Time.new w.highs.each_with_index { |high, i| next if i == 0 # skip todays forecast date += 86400 day = date.strftime("%a") precip = w.precips[i] s << sprintf("%s: %s (%s)", day, high, precip) # Sun: 80F (10%) break if i == 6 # only want to show the next 6 days } m.reply(s.join(' ')) end def get_sourceaddress(m) source = m.sourceaddress (ident, host) = source.split(/@/) quads = host.split(/\./) if quads.size > 3 then source = "#{ident}@*." + quads[quads.size-3,quads.size].join(".") end return source end def check_zip(m, params) source = get_sourceaddress(m) if params[:zip] then zip = params[:zip] # store it if we have nothing on file for them if not @registry.has_key? source then @registry[source] = params[:zip] m.reply("hi %s. I went ahead and set %s as your default zip. You can change it with the command tw default <zip>" % [ m.sourcenick, params[:zip] ]) end return zip elsif @registry.has_key? source then return @registry[source] else m.reply("zipcode is required the first time you call me") return nil end end def do_set_default(m, params) source = get_sourceaddress(m) if not params[:zip] then return m.reply("%s, I can't very well set a new default for you without a zipcode, can I?" % m.sourcenick) end @registry[source] = params[:zip] m.reply "%s, your default zip has been set to %s" % [ m.sourcenick, params[:zip] ] # and give em the weather while we're at it do_tiny_weather(m, params) end def scrape_hourly_weather(zip) html = fetchurl("http://www.weather.com/weather/hourbyhour/graph/#{zip}?pagenum=2&nextbeginIndex=0") hour_scraper = Scraper.define do process "h3.wx-time", :hour => :text process_first "div.wx-conditions p.wx-temp", :temp => :text process_first "div.wx-details dl:nth-child(3) dd", :precip => :text result :hour, :temp, :precip end hourly_scraper = Scraper.define do array :hours process "div.wx-timepart", :hours => hour_scraper process "div.wx-location-title > h1", :location => :text result :location, :hours end w = hourly_scraper.scrape(html) w.hours.each { |h| if h.hour =~ /^(\d+ [A-Z]{2})/ then h.hour = $1 h.hour.downcase! end clean(h.temp, 'F') clean(h.precip, '%') } w.location.gsub!(/\s+Weather\s*$/, '') w.location.strip! return w end def clean(str, replace='') str.gsub!(/&#176;.?/, replace) end def scrape_weather_forecast(zip) html = fetchurl('http://www.weather.com/weather/tenday/' + zip) fc_scraper = Scraper.define do array :highs, :lows, :precips process "p.wx-temp", :highs => :text process "p.wx-temp-alt", :lows => :text process "div.wx-details dl dd", :precips => :text process_first "div.wx-location-title > h1", :location => :text result :location, :highs, :lows, :precips end w = fc_scraper.scrape(html) # cleanup results w.location.gsub!(/\s+Weather\s*$/, '') w.location.strip! w.highs.each { |h| clean(h, 'F') } w.lows.each { |h| clean(h, 'F') } w.precips.each { |h| clean(h, '%') } w.precips = w.precips.find_all { |h| h =~ /%$/ } return w end end plugin = TinyWeatherPlugin.new plugin.map 'tw default :zip', :action => 'do_set_default' plugin.map 'tw [:zip]', :action => 'do_tiny_weather' plugin.map 'twf [:zip]', :action => 'do_tiny_weather_forecast'
ploch/rbot
plugins/quietube.rb
<reponame>ploch/rbot # quietube # by <NAME> <<EMAIL>> 2009-11-24 # # posts shortened quietube version of youtube links with optional title require '0lib_rbot' require 'shorturl' class QuietubePlugin < Plugin include PluginLib Config.register Config::BooleanValue.new("quietube.display_title", :default => false, :desc => "Fetch and display video title") def initialize super self.filter_group = :htmlinfo load_filters end def listen(m) return unless m.kind_of?(PrivMessage) urls = extract_urls(m) urls.each { |url| next if url !~ %r{http://www\.youtube\.com/watch\?v=} title = nil if @bot.config["quietube.display_title"] then # get title uri = url.kind_of?(URI) ? url : URI.parse(url) info = @bot.filter(:htmlinfo, uri) title = info[:title] title = " -> #{title}" if not title.nil? end quieter = "http://quietube.com/v.php/#{url}" link = ShortURL.shorten(quieter, :tinyurl) m.reply "quieter: #{link}#{title}" } end end plugin = QuietubePlugin.new plugin.register("quietube")
ploch/rbot
plugins/scrambler.rb
<reponame>ploch/rbot # TODO: # warn near end of game # scores update during game # alltime scores # win count require 'jcode' require 'pathname' class Scrambler attr :active attr :current_word attr :current_word_rnd attr :current_word_t attr :current_hint attr :hints attr :hints_remaining attr :word_list attr :scores attr :leader attr :leader_points def initialize @active = false end def start_game(word_list = 'mixed', num_words = 20) @active = true @scores = {} @word_list = get_word_list(word_list, num_words) next_word() end def end_game @current_word = @current_word_t = @current_word_rnd = @current_hint = @hints = @hints_remaining = nil @active = false end def active? @active end def score(player) @scores[player] end # returns a descending list of players by score # [ [player,score], [player,score], ... ] def get_scores @scores.sort { |a,b| b[1] <=> a[1] } end def guess(player, str) #log sprintf("checking if `%s' == `%s'", str, @current_word) if @current_word == str then # winnar! # ugly: @scores[player] = @scores.has_key? player ? @scores[player] + 1 : 1 add_point(player) next_word() return true else return false end end def add_point(player) # give him the point if @scores.has_key? player then @scores[player] += 1 else @scores[player] = 1 end old_leader = @leader cur_leader = get_scores()[0] if old_leader.nil? or old_leader.empty? or (old_leader != cur_leader[0] and @leader_points < cur_leader[1]) then # leader change! @leader = cur_leader @leader_points = cur_leader[1] end end def hint word = @current_word hint_size = 3 hint_size = 4 if word.length >= 10 hint_size = 5 if word.length >= 20 if @hints.nil? or @hints.empty? then @hints = [] (0..word.length).each { |i| @hints << i if word[i,1] == ' ' } @hints.push( 0, word.length, (word.length / 2).round ) else # get 3 more hints, if available @hints_remaining.shuffle[0, hint_size].each { |h| @hints << h } end hint = '' (0..word.length).each { |i| if @hints.include? i then hint += word[i,1] else hint += '_' @hints_remaining << i end } hint end def skip_word next_word() end # --- END PUBLIC INTERFACE --- # private def next_word return end_game() if @word_list.empty? @current_word = @word_list.pop @current_word_t = Time.new @current_word_rnd = shuffle_chars(@current_word) @current_hint = nil @hints = @hints_remaining = [] end # get a randomized word list by name. # 'mixed' for a combination of all available lists def get_word_list(list = 'mixed', num_words = 20) filename = File.expand_path( File.dirname(__FILE__) ) + "/scrambler_" + list + ".txt" raise "list not found" if not File.exist? filename words = File.new(filename).readlines.map! { |w| w.strip }.map { |w| w.downcase if not w.empty? } return words.shuffle[0, num_words] end # shuffle a string def shuffle_chars(str) s = str.dup sz = s.length (0...sz).each { |j| i = rand(sz-j) s[j], s[j+i] = s[j+i], s[j] } s end end class ScramblerPlugin < Plugin attr :games def initialize super @games = {} end def listen(m) return unless m.respond_to?(:public?) and m.public? return unless @games.has_key? m.channel and @games[m.channel].active? # active game, looking for guesses game = @games[m.channel] player = m.source guess = m.plainmessage.strip #log sprintf("player `%s' guessed `%s'", player, guess) leader = game.leader if game.guess(player, guess) then # got it! str = sprintf( "%s guessed correctly with `%s'.", player, guess ) if leader != game.leader then str += sprintf(" they've taken the lead with %s points!", game.leader_points) else str += sprintf( " they now have %s points", game.score(player) ) end m.reply str next_word(m, game) end end def do_start(m, params) return do_word(m, params, "game already in progress!") if @games.has_key? m.channel and @games[m.channel].active? @games[m.channel] = game = Scrambler.new game.start_game(params[:word_list], params[:num_words].to_i) next_word(m, game) end def do_end(m, params) return m.reply "no game in progress!" if not @games.has_key? m.channel m.reply "the game has been ended :(" game = @games[m.channel] game.end_game end_game(m, game) end def do_scores(m, params) return m.reply "no game in progress!" if not @games.has_key? m.channel game = @games[m.channel] show_scores(m, game) end def do_stats(m, params) end def do_skip(m, params) return m.reply "no game in progress!" if not @games.has_key? m.channel game = @games[m.channel] game.skip_word next_word(m, game) end def do_hint(m, params) return m.reply "no game in progress!" if not @games.has_key? m.channel game = @games[m.channel] m.reply "hint: " + game.hint end def do_word(m, params, extra = '') return m.reply "no game in progress!" if not @games.has_key? m.channel game = @games[m.channel] m.reply extra + "current word: " + game.current_word_rnd end def do_list(m, params) lists = [] path = File.expand_path( File.dirname(__FILE__) ) Pathname.new(path).each_entry { |e| lists << $1 if e.to_s =~ /scrambler_(.*)\.txt/ } m.reply "available word lists: " + lists.sort.join(', ') end # private methods def next_word(m, game) if not game.active? then # ran out of words m.reply "that was the last word!" return end_game(m, game) end m.reply "new word: " + game.current_word_rnd end def end_game(m, game) scores = game.get_scores return if scores.empty? winner = scores[0] m.reply sprintf("%s won with %s points!", winner[0], winner[1]) show_scores(m, game) end def show_scores(m, game) scores = game.get_scores scores.collect! { |s| sprintf("%s: %s", s[0], s[1]) } m.reply scores.join(', ') end end pg = ScramblerPlugin.new pg.map 'scrambler [:word_list] [:num_words]', :private => false, :action => :do_start, :defaults => { :word_list => 'mixed', :num_words => 20 }, :requirements => { :num_words => %r|\d+| } pg.map 'sc end', :private => false, :action => :do_end pg.map 'sc scores', :private => false, :action => :do_scores pg.map 'sc stats', :private => false, :action => :do_stats pg.map 'sc skip', :private => false, :action => :do_skip pg.map 'sc hint', :private => false, :action => :do_hint pg.map 'sc word', :private => false, :action => :do_word pg.map 'sc lists', :private => false, :action => :do_list pg.map 'sc [:word_list] [:num_words]', :private => false, :action => :do_start, :defaults => { :word_list => 'mixed', :num_words => 20 }, :requirements => { :num_words => %r|\d+| }
sky-uk/java-buildpack
lib/java_buildpack/framework/ruxit_agent.rb
<reponame>sky-uk/java-buildpack<filename>lib/java_buildpack/framework/ruxit_agent.rb<gh_stars>10-100 # Encoding: utf-8 # Cloud Foundry Java Buildpack # Copyright 2013-2016 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'fileutils' require 'java_buildpack/component/versioned_dependency_component' require 'java_buildpack/framework' module JavaBuildpack module Framework # Encapsulates the functionality for enabling zero-touch Ruxit support. class RuxitAgent < JavaBuildpack::Component::VersionedDependencyComponent # (see JavaBuildpack::Component::BaseComponent#compile) def compile download(@version, @uri) { |file| expand file } @droplet.copy_resources end # (see JavaBuildpack::Component::BaseComponent#release) def release credentials = @application.services.find_service(FILTER)['credentials'] @droplet.java_opts.add_agentpath_with_props(agent_path, SERVER => server(credentials), TENANT => tenant(credentials), TENANTTOKEN => tenanttoken(credentials)) environment = @application.environment environment_variables = @droplet.environment_variables unless environment.key?(RUXIT_APPLICATION_ID) environment_variables.add_environment_variable(RUXIT_APPLICATION_ID, application_id) end unless environment.key?(RUXIT_CLUSTER_ID) environment_variables.add_environment_variable(RUXIT_CLUSTER_ID, cluster_id) end environment_variables.add_environment_variable(RUXIT_HOST_ID, host_id) unless environment.key?(RUXIT_HOST_ID) end protected # (see JavaBuildpack::Component::VersionedDependencyComponent#supports?) def supports? @application.services.one_service? FILTER, TENANT, TENANTTOKEN end private FILTER = /ruxit|dynatrace/ RUXIT_APPLICATION_ID = 'RUXIT_APPLICATIONID'.freeze RUXIT_CLUSTER_ID = 'RUXIT_CLUSTER_ID'.freeze RUXIT_HOST_ID = 'RUXIT_HOST_ID'.freeze SERVER = 'server'.freeze TENANT = 'tenant'.freeze TENANTTOKEN = '<PASSWORD>'.freeze private_constant :FILTER, :RUXIT_APPLICATION_ID, :RUXIT_CLUSTER_ID, :RUXIT_HOST_ID, :SERVER, :TENANT, :TENANTTOKEN def agent_dir @droplet.sandbox + 'agent' end def agent_path agent_dir + 'lib64/libruxitagentloader.so' end def application_id @application.details['application_name'] end def cluster_id @application.details['application_name'] end def expand(file) with_timing "Expanding Ruxit Agent to #{@droplet.sandbox.relative_path_from(@droplet.root)}" do Dir.mktmpdir do |root| root_path = Pathname.new(root) shell "unzip -qq #{file.path} -d #{root_path} 2>&1" unpack_agent root_path end end end def host_id "#{@application.details['application_name']}_${CF_INSTANCE_INDEX}" end def server(credentials) credentials[SERVER] || "https://#{tenant(credentials)}.live.ruxit.com:443/communication" end def tenant(credentials) credentials[TENANT] end def tenanttoken(credentials) credentials[TENANTTOKEN] end def unpack_agent(root) FileUtils.mkdir_p(@droplet.sandbox) FileUtils.mv(root + 'agent', @droplet.sandbox) end end end end
MGat22/playingaround
web_greeter.rb
<reponame>MGat22/playingaround require 'sinatra' get '/:name' do name = params[:name] "Hello #{name}! Did you know your name has #{name.length} letters in it and written backwards it is #{name.reverse.downcase.capitalize}?" end
MGat22/playingaround
hello_sinatra.rb
require 'sinatra' get '/hello' do "Hello Sinatra!" end
MGat22/playingaround
greeter.rb
<reponame>MGat22/playingaround puts "Please enter your name:" name = gets.chomp puts "Hello #{name}! Did you know your name has #{name.length} letters in it and written backwards it is #{name.reverse.downcase.capitalize}?"
MGat22/playingaround
web_madlibs.rb
<filename>web_madlibs.rb require 'sinatra' get '/madlibs'do erb :questions end post '/madlibs' do animal = params[:animal] color = params[:color] person = params[:person] object = params[:object] adjective = params[:adjective] verb = params[:verb] "The #{adjective} #{animal} started to #{verb} because the #{person} ran away with the #{color} #{object}" end __END__ @@questions <!doctype html> <html> <header> <title>Madlibs</title> </header> <body> <form method="POST" actions="/madlibs"> <p>Animal:</p> <input name="animal"> <p>Color:</p> <input name="color"> <p>Person:</p> <input name="person"> <p>Object:</p> <input name="object"> <p>Adjective:</p> <input name="adjective"> <p>Verb:</p> <input name="verb"> <input type="submit" value="Create Madlibs"> </form> </body> </html>
MGat22/playingaround
madlibs.rb
<gh_stars>0 puts "Please enter the name of an animal:" animal = gets.chomp puts "Please enter a color:" color = gets.chomp puts "Please enter a type of person:" person = gets.chomp puts "Please enter an object:" object = gets.chomp puts "Please enter an adjective:" adjective = gets.chomp puts "Please enter a verb:" verb = gets.chomp puts "The #{adjective} #{animal} started to #{verb} because the #{person} ran away with the #{color} #{object}"
MGat22/playingaround
hello_ruby.rb
#This is my first Ruby program! puts "Hello Ruby!" puts 1+1 3.times do puts "Ruby!" end
chainuser1/library
app/models/photo.rb
<gh_stars>0 class Photo < ActiveRecord::Base mount_uploader :attachment, AttachmentUploader #Tells rails to use this uploader for this model belongs_to :user,foreign_key: :user_username, primary_key: 'username', dependent: :destroy validates :name, presence: true validates :attachment, presence: true end
chainuser1/library
db/migrate/20160316183356_create_carts.rb
<reponame>chainuser1/library class CreateCarts < ActiveRecord::Migration def change create_table :carts, id: false do |t| t.string :book_isbn t.string :user_username t.timestamps null: false end end end
chainuser1/library
app/models/book.rb
class Book < ActiveRecord::Base self.primary_key=:isbn def to_param isbn end ISBN_REGEX_CHECKER=/(ISBN[-]*(1[03])*[ ]*(: ){0,1})*(([0-9Xx][- ]*){13}|([0-9Xx][- ]*){10})/ AUTHOR_REGEX=/\A[A-z][A-z|\.|\s]+\z/ validates :isbn, presence: true, format: {with: ISBN_REGEX_CHECKER, message: ' is not a valid.'}, uniqueness: true validates :title, presence: true validates :category, presence: true validates :publisher, presence: true validates :copyright, presence: true validates :description, presence: true, length: {minimum: 100, maximum: 2500} belongs_to :author, dependent: :destroy has_many :carts, foreign_key: :book_isbn, primary_key: :isbn, dependent: :destroy has_many :users, through: :carts, foreign_key: :book_isbn, primary_key: :isbn end
chainuser1/library
app/helpers/application_helper.rb
<reponame>chainuser1/library module ApplicationHelper # Returns the full title on a per-page basis. def full_title(page_title = '') base_title = "the Library" if page_title.empty? base_title else page_title + " | " + base_title end end def profile_page_heading(heading='') profile_heading='Profile' if heading.empty? profile_heading else profile_heading + ": " + heading end end end
chainuser1/library
app/controllers/welcomes_controller.rb
<reponame>chainuser1/library class WelcomesController < ApplicationController def index end def maintenance end end
chainuser1/library
app/models/profile.rb
class Profile < ActiveRecord::Base self.primary_key='user_username' #mutators def fname=(fname) self[:fname]=fname.capitalize end def lname=(lname) self[:lname]=lname.capitalize end def address=(address) self[:address]=address.capitalize end belongs_to :user, class_name: 'User',foreign_key: :user_username, primary_key: 'username', dependent: :destroy REGEX_EMAIL_PATTERN=/([a-z0-9_]|[a-z0-9_]+\.[a-z0-9_]+)@(([a-z0-9]|[a-z0-9]+\.[a-z0-9]+)+\.([a-z]{2,4}))/i #validate form validates :fname, presence: true validates :lname, presence: true validates :gender, presence:true validates :email, presence:true,uniqueness:true, format: {with: REGEX_EMAIL_PATTERN} validates :address, presence:true validates :birthdate, presence: true end
chainuser1/library
db/migrate/20160304170831_add_index_to_profiles.rb
<gh_stars>0 class AddIndexToProfiles < ActiveRecord::Migration def change add_foreign_key :profiles, :users, column: :user_username, primary_key: "username", on_delete: :cascade, on_update: :cascade end end
chainuser1/library
app/helpers/auths_helper.rb
<gh_stars>0 module AuthsHelper def log_in(user) session[:user_username]=user.username session[:user_role]=user.role end def current_user @current_user ||= User.find_by(username: session[:user_username]) end def logged_in? !current_user.nil? end def authenticate_user if !logged_in? redirect_to login_auths_path end end def is_admin? if session[:user_role]==0 return true else return false end end =begin Profile Checker if there is a profile associated with a specific user =end def profile_checker? user=User.find_by(username: current_user.username) if !user.profile.nil? return true else return false end end end
chainuser1/library
test/controllers/books_controller_test.rb
<filename>test/controllers/books_controller_test.rb require 'test_helper' class BooksControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success end test "should get show" do get :show assert_response :success end test "should get new" do get :new assert_response :success end test "should get create" do get :create assert_response :success end test "should get edit" do get :edit assert_response :success end test "should get update" do get :update assert_response :success end test "should get remove" do get :remove assert_response :success end test "should get show_old" do get :show_old assert_response :success end test "should get show_new" do get :show_new assert_response :success end test "should get search" do get :search assert_response :success end end
chainuser1/library
app/models/cart.rb
<gh_stars>0 class Cart < ActiveRecord::Base self.primary_key='id' belongs_to :user, foreign_key: :user_username, :primary_key => 'username' belongs_to :book, foreign_key: :book_isbn, :primary_key => 'isbn' end
chainuser1/library
config/initializers/assets.rb
<gh_stars>0 # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js ) Rails.application.config.assets.precompile += %w( bootstrap.min.css ) Rails.application.config.assets.precompile += %w( bootstrap.min.js ) Rails.application.config.assets.precompile += %w( jquery.min.js ) Rails.application.config.assets.precompile += %w( bootstrap-theme.min.css ) Rails.application.config.assets.precompile += %w( costume-application.js ) Rails.application.config.assets.precompile += %w( foundation.min.css ) Rails.application.config.assets.precompile += %w( foundation-rtl.css ) Rails.application.config.assets.precompile += %w( foundation-flex.css ) Rails.application.config.assets.precompile += %w( foundation.min.js ) Rails.application.config.assets.precompile += %w( bg.jpg ) Rails.application.config.assets.precompile += %w( writing.jpg ) Rails.application.config.assets.precompile += %w( read.jpg ) Rails.application.config.assets.precompile += %w( piano-stair.jpg ) Rails.application.config.assets.precompile += %w( learned.jpg ) Rails.application.config.assets.precompile += %w( picedit.css ) Rails.application.config.assets.precompile += %w( picedit.js )
chainuser1/library
app/controllers/tasks_controller.rb
class TasksController < ApplicationController def show_reservations @carts=Cart.all.paginate(:per_page=>5,:page => params[:reservations]).order('created_at DESC') end def show_all_users @users=User.all.paginate(:per_page=>5,:page => params[:users]).order('username ASC') end end
chainuser1/library
app/controllers/book_types_controller.rb
<reponame>chainuser1/library class BookTypesController < ApplicationController layout 'application' def new @book_type=BookType.new end def create @book_type=BookType.new(params.require(:@book_type).permit(:category)) respond_to do |format| if @book_type.save format.json {render json: @book_type} format.js {render :layout => true} else format.json {render json: @book_type} format.js {render :layout => true} end end end def destroy end end
chainuser1/library
test/controllers/auth_controller_test.rb
require 'test_helper' class AuthControllerTest < ActionController::TestCase test "should get login" do get :login assert_response :success end test "should get verify" do get :verify assert_response :success end test "should get logout" do get :logout assert_response :success end end
chainuser1/library
app/controllers/photos_controller.rb
<reponame>chainuser1/library class PhotosController < ApplicationController def index @photos=current_user.photos.paginate(:per_page=>20,:page=>params[:photos] ) end def new @photo=Photo.new end def create @photo=Photo.new(photo_params) respond_to do |format| if @photo.save format.html {redirect_to photos_path, notice: "The #{@photo.name} has been uploaded"} else format.html{render 'new'} format.js {} end end end def destroy @photo=Photo.find(param[:id]) @photo.destroy redirect_to photos_path, notice: "The photo #{@photo.name} has been deleted" end private def photo_params params.require(:photo).permit(:user_username,:name,:attachment) end end
chainuser1/library
db/migrate/20160211183340_create_add_user_role_to_users.rb
class CreateAddUserRoleToUsers < ActiveRecord::Migration def change # create_table :add_user_role_to_users do |t| add_column :users, :role, :integer, default: 1 end end
chainuser1/library
app/views/authors/show.json.jbuilder
<reponame>chainuser1/library<filename>app/views/authors/show.json.jbuilder json.extract! @author, :id,:name, :biography, :created_at, :updated_at
chainuser1/library
app/controllers/application_controller.rb
<filename>app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception include AuthsHelper include UsersHelper require "will_paginate-bootstrap" end
chainuser1/library
db/migrate/20160216170423_create_add_unique_category_to_book_types.rb
<gh_stars>0 class CreateAddUniqueCategoryToBookTypes < ActiveRecord::Migration def change add_index :book_types,:category, unique: true end end
chainuser1/library
app/helpers/book_types_helper.rb
module BookTypesHelper end
chainuser1/library
app/controllers/auths_controller.rb
class AuthsController < ApplicationController layout 'application' def login if logged_in? redirect_to root_path else render 'login' end end def verify user = User.find_by(username: params[:user][:username]) #render plain: user && user.authenticate(params[:user][:password])? true : false if user && user.authenticate(params[:user][:password]) log_in user redirect_to root_path else flash[:danger] = 'Invalid email/password combination' # Not quite right! render 'login' end end def logout reset_session redirect_to root_path end end
chainuser1/library
app/helpers/books_helper.rb
module BooksHelper def book_page_heading(heading='') book_heading='Books: ' if heading.empty? book_heading else heading end end end
chainuser1/library
app/controllers/profiles_controller.rb
<filename>app/controllers/profiles_controller.rb class ProfilesController < ApplicationController layout 'application' before_action :authenticate_user#, :except=>[] before_action :set_profile,:only=>[:change,:new,:update,:manifest,:remove] def index end def new if !@profile.nil? redirect_to manifest_profile_path(current_user.username) else @profile=Profile.new end end def create @profile=current_user.create_profile(profile_params) respond_to do |format| if @profile.save format.html {redirect_to manifest_profile_path(current_user.username)} format.json {render :manifest, status: :created, location: @profile} else format.html{render 'new'} format.json { render json: @profile.errors, status: :unprocessable_entity } end end end def manifest if profile_checker? render 'show' else redirect_to new_profile_path end end def change render 'edit' end def update respond_to do |format| if @profile.update(profile_params) format.html {redirect_to manifest_profile_path} format.json {render :manifest, status: :created, location: @profile} else render 'edit' format.json { render json: @profile.errors, status: :unprocessable_entity } end end end def delete end def remove @profile.delete redirect_to logout_auths_path end private def profile_params params.require(:profile).permit(:user_username,:fname,:lname,:gender,:email,:address, :birthdate) end def set_profile @profile=current_user.profile end end
chainuser1/library
app/models/book_type.rb
<gh_stars>0 class BookType < ActiveRecord::Base def category=(category)#mutator self[:category]=category.capitalize end validates :category, presence: true, uniqueness: true end
chainuser1/library
app/controllers/users_controller.rb
class UsersController < ApplicationController require 'bcrypt' layout 'application' def new if logged_in? redirect_to root_path else @user=User.new end end def register @user=User.new(user_params_register) respond_to do |format| if @user.save format.html {redirect_to root_path} else format.html {render 'new'} end end end private def user_params_register params.require(:user).permit(:username,:password,:password_confirmation) end end
chainuser1/library
app/helpers/profiles_helper.rb
module ProfilesHelper end
chainuser1/library
app/models/user.rb
class User < ActiveRecord::Base self.primary_key='username' has_one :profile, class_name: 'Profile',primary_key: 'username', foreign_key: 'user_username' has_many :photos, foreign_key: :user_username, primary_key: 'username' has_many :carts, foreign_key: :user_username, primary_key: :username,dependent: :destroy has_many :books, through: :carts, foreign_key: :user_username, primary_key: :username validates :username ,presence:true, uniqueness: true, format: {with: /\A[[:alnum:]]+(?:[-_\. ]?[[:alnum:]]+)*\Z/} has_secure_password validates :password, presence:true, length: {minimum: 8, maximum: 32 , message: ' must be between 8-32 characters.'} end
chainuser1/library
db/schema.rb
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20160329180824) do create_table "authors", force: :cascade do |t| t.string "name", limit: 255 t.text "biography", limit: 65535 t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "book_types", force: :cascade do |t| t.string "category", limit: 255 t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "book_types", ["category"], name: "index_book_types_on_category", unique: true, using: :btree create_table "books", id: false, force: :cascade do |t| t.string "isbn", limit: 255 t.string "title", limit: 255 t.string "author", limit: 255 t.string "category", limit: 255 t.string "publisher", limit: 255 t.date "copyright" t.text "description", limit: 65535 t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "author_id", limit: 4 end add_index "books", ["author_id"], name: "fk_rails_53d51ce16a", using: :btree add_index "books", ["isbn"], name: "index_books_on_isbn", unique: true, using: :btree create_table "carts", id: false, force: :cascade do |t| t.string "book_isbn", limit: 255 t.string "user_username", limit: 255 t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "photos", force: :cascade do |t| t.string "user_username", limit: 255 t.string "name", limit: 255 t.string "attachment", limit: 255 t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "profiles", id: false, force: :cascade do |t| t.string "user_username", limit: 255 t.string "fname", limit: 255 t.string "lname", limit: 255 t.string "gender", limit: 255 t.string "email", limit: 255 t.string "address", limit: 255 t.date "birthdate" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "profiles", ["email"], name: "index_profiles_on_email", unique: true, using: :btree add_index "profiles", ["user_username"], name: "fk_rails_31b749ed17", using: :btree create_table "users", primary_key: "username", force: :cascade do |t| t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "password_digest", limit: 255 t.integer "role", limit: 4, default: 1 end add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree add_foreign_key "books", "authors", on_delete: :cascade add_foreign_key "profiles", "users", column: "user_username", primary_key: "username", on_update: :cascade, on_delete: :cascade end
chainuser1/library
db/migrate/20160308171211_add_unique_email_attribute_to_profiles.rb
class AddUniqueEmailAttributeToProfiles < ActiveRecord::Migration def change add_index :profiles,:email, unique: true end end
chainuser1/library
app/helpers/users_helper.rb
module UsersHelper def find_dp if logged_in? user=User.find_by(username: current_user.username) photos=user.photos.order('updated_at DESC').limit(1) photos.each do |photo| return photo.attachment_url end else return nil end end end
chainuser1/library
test/controllers/reeks_controller_test.rb
require 'test_helper' class ReeksControllerTest < ActionController::TestCase setup do @reek = reeks(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:reeks) end test "should get new" do get :new assert_response :success end test "should create reek" do assert_difference('Reek.count') do post :create, reek: { lantern: @reek.lantern, reek_id: @reek.reek_id } end assert_redirected_to reek_path(assigns(:reek)) end test "should show reek" do get :show, id: @reek assert_response :success end test "should get edit" do get :edit, id: @reek assert_response :success end test "should update reek" do patch :update, id: @reek, reek: { lantern: @reek.lantern, reek_id: @reek.reek_id } assert_redirected_to reek_path(assigns(:reek)) end test "should remove reek" do assert_difference('Reek.count', -1) do delete :remove, id: @reek end assert_redirected_to reeks_path end end
chainuser1/library
db/migrate/20160211175243_create_add_isbn_unique_to_books.rb
<reponame>chainuser1/library<filename>db/migrate/20160211175243_create_add_isbn_unique_to_books.rb<gh_stars>0 class CreateAddIsbnUniqueToBooks < ActiveRecord::Migration def change add_index :books, :isbn, unique: true end end
chainuser1/library
app/views/profiles/manifest.json.jbuilder
<reponame>chainuser1/library json.extract! @profile, :user_username,:fname,:lname,:gender,:email,:address, :birthdate,:created_at,:updated_at
chainuser1/library
db/migrate/20160309181823_add_foriegn_key_to_books.rb
class AddForiegnKeyToBooks < ActiveRecord::Migration def change add_column :books, :author_id, :integer add_foreign_key :books, :authors, column: :author_id, primary_key: 'id', on_delete: :cascade end end
chainuser1/library
db/migrate/20160203201937_create_users.rb
<filename>db/migrate/20160203201937_create_users.rb class CreateUsers < ActiveRecord::Migration def change create_table :users, id:false do |t| t.string :username t.timestamps null: false end execute "ALTER TABLE users ADD PRIMARY KEY (username);" end end
chainuser1/library
db/migrate/20160203220336_create_add_password_digest_to_users.rb
<reponame>chainuser1/library<gh_stars>0 class CreateAddPasswordDigestToUsers < ActiveRecord::Migration def change add_column :users, :password_digest, :string add_index :users, :username, unique:true end end
chainuser1/library
app/controllers/carts_controller.rb
class CartsController < ApplicationController def index @carts=current_user.carts end def create @book=Book.find_by(isbn: params[:isbn]) @cart=@book.carts.create(user_username: current_user.username) if @cart.save redirect_to books_path else redirect_to maintenance_welcome_path end end def delete cart=Cart.find_by(book_isbn: params[:isbn], user_username: current_user.username) cart.destroy() redirect_to books_path end def delmodal cart=Cart.find_by(book_isbn: params[:isbn], user_username: current_user.username) if cart.destroy() render plain: 'Item removed' else render plain: 'Item was not removed' end end end
chainuser1/library
app/controllers/books_controller.rb
class BooksController < ApplicationController before_action :set_book, only: [:edit,:update,:delete,:remove,:show,:tranquility_cdn] before_action :set_author, only: [:create,:update] include BooksHelper layout 'application' def index @books=Book.all.paginate(:per_page=>5,:page => params[:page]).order('title ASC') end def show render 'show' end def manifest #get results #search results will be displayed here respond_to do |format| if params[:book][:isbn].present? @books=Book.where('isbn=?',params[:book][:isbn]) .paginate(:per_page=>5,:page=>params[:page]) #title and likes elsif params[:book][:title].present? @books=Book.where('title LIKE ?',"%"+params[:book][:title]+"%").order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) if params[:book][:author_id].present? #author is present @books=Book.where('title LIKE ? and author_id = ?',"%"+params[:book][:title]+"%",params[:book][:author_id]).order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) if params[:book][:category].present? @books=Book.where('title LIKE ? and author_id = ? and category=?', "%"+params[:book][:title]+"%",params[:book][:author_id],params[:book][:category]).order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) if params[:book][:publisher].present? @books=Book.where('title LIKE ? and author_id = ? and category=? and publisher LIKE ?', "%"+params[:book][:title]+"%",params[:book][:author_id],params[:book][:category], "%"+params[:book][:publisher]+"%").order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) end end elsif params[:book][:category].present? @books=Book.where('title LIKE ? and category=?',"%"+params[:book][:title]+"%",params[:book][:category]).order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) if params[:book][:publisher].present? @books=Book.where('title LIKE ? and category=? and publisher LIKE ?',"%"+params[:book][:title]+"%",params[:book][:category],"%"+params[:book][:publisher]+"%").order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) end elsif params[:book][:publisher].present? @books=Book.where('title LIKE ? and publisher like ?',"%"+params[:book][:title]+"%","%"+params[:book][:publisher]+"%").order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) end #author and likes elsif params[:book][:author_id].present? @books=Book.where('author_id = ?',params[:book][:author_id]).order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) if params[:book][:category].present? @books=Book.where('author_id = ? and category=?',params[:book][:author_id],params[:book][:category]).order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) if params[:book][:publisher].present? @books=Book.where('author_id = ? and category=? and publisher like ?',params[:book][:author_id],params[:book][:category],"%"+params[:book][:publisher]+"%").order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) end end elsif params[:book][:category].present? @books=Book.where('category=?',params[:book][:category]).order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) if params[:book][:publisher].present? @books=Book.where('category=? and publisher like ?',params[:book][:category],"%"+params[:book][:publisher]+"%").order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) end elsif params[:book][:publisher].present? @books=Book.where("publisher like ?","%"+params[:book][:publisher]+"%").order('title ASC') .paginate(:per_page=>5,:page=>params[:page]) end format.html {render 'manifest'} end end def new @book=Book.new end def create @book=@author.books.create(book_params) respond_to do |format| if @book.save format.json {render json: @book} format.js {} else format.json {render json: @book} format.js {} end end end def edit end def update #render plain: params[:isbn] respond_to do |format| if @book.update(book_params) format.json {render json: @book} format.js {} else format.json {render json: @book} format.js {} end end end def tranquility_cdn end def delete end def remove @index=params[:isbn] @book=@book.delete end def show_old @books=Book.all.paginate(:per_page=>5,:page => params[:page]).order('copyright DESC').limit(20) end def show_new end def search end private def set_book @book=Book.find(params[:isbn]) end def book_params params.require(:book).permit :isbn,:title, :category,:publisher, :copyright,:description, :author_id end def set_author @author=Author.find_or_initialize_by(id: params[:book][:author_id]) end end
chainuser1/library
db/migrate/20160229194532_create_profiles.rb
<reponame>chainuser1/library class CreateProfiles < ActiveRecord::Migration def change create_table :profiles , id: false do |t| t.string :user_username t.string :fname t.string :lname t.string :gender t.string :email t.string :address t.date :birthdate t.timestamps null: false end end end
tbanish/js-flashcard-backend
db/migrate/20210603183130_create_tests.rb
<gh_stars>0 class CreateTests < ActiveRecord::Migration[6.0] def change create_table :tests do |t| t.integer :duration t.float :score t.string :correct_ids t.string :incorrect_ids t.integer :deck_id t.timestamps end end end
tbanish/js-flashcard-backend
db/migrate/20210603183954_add_correct_answers_to_cards.rb
<gh_stars>0 class AddCorrectAnswersToCards < ActiveRecord::Migration[6.0] def change add_column :cards, :correct_answers, :integer end end
tbanish/js-flashcard-backend
app/models/card.rb
<gh_stars>0 class Card < ApplicationRecord belongs_to :deck validates :answer, :question, presence: true end
tbanish/js-flashcard-backend
app/models/deck.rb
class Deck < ApplicationRecord has_many :cards, dependent: :destroy has_many :tests validates :subject, presence: true, uniqueness: true end
tbanish/js-flashcard-backend
app/models/test.rb
class Test < ApplicationRecord belongs_to :deck end
tbanish/js-flashcard-backend
app/controllers/api/v1/tests_controller.rb
<gh_stars>0 class Api::V1::TestsController < ApplicationController def index tests = Test.all render json: TestSerializer.new(tests) end def create test = Test.new(test_params) if test.save render json: test, status: :accepted else render json: { errors: test.errors.full_messages } end end private def test_params params.require(:test).permit(:duration, :score, :correct_ids, :incorrect_ids, :deck_id) end end
tbanish/js-flashcard-backend
app/controllers/api/v1/cards_controller.rb
class Api::V1::CardsController < ApplicationController def index cards = Card.all render json: CardSerializer.new(cards) end def show card = Card.find_by(id: params[:id]) render json: CardSerializer.new(card) end def create card = Card.new(card_params) if card.save render json: card, status: :accepted else render json: { errors: card.errors.full_messages } end end def update card = Card.find_by(id: params[:id]) card.update(card_params) if card.save render json: card, status: :accepted else render json: { errors: card.errors.full_messages } end end def destroy card = Card.find_by(id: params[:id]) card.destroy end private def card_params params.require(:card).permit(:question, :answer, :deck_id) end end
tbanish/js-flashcard-backend
app/serializers/card_serializer.rb
<filename>app/serializers/card_serializer.rb class CardSerializer include FastJsonapi::ObjectSerializer attributes :question, :answer, :deck_id, :deck end
tbanish/js-flashcard-backend
app/serializers/deck_serializer.rb
class DeckSerializer include FastJsonapi::ObjectSerializer attributes :subject, :cards end
tbanish/js-flashcard-backend
app/serializers/test_serializer.rb
<filename>app/serializers/test_serializer.rb class TestSerializer include FastJsonapi::ObjectSerializer attributes :duration, :score, :correct_ids, :incorrect_ids, :deck_id, :created_at end
gumdal/KKGridView
KKGridView.podspec
<gh_stars>10-100 Pod::Spec.new do |s| s.name = 'KKGridView' s.version = '0.6.8.2' s.license = 'MIT' s.platform = :ios s.summary = 'Gridview for iOS.' s.homepage = 'https://github.com/kolinkrewinkel/KKGridView' s.authors = { '<NAME>' => '<EMAIL>', '<NAME>' => '<EMAIL>', '<NAME>' => '<EMAIL>', '<NAME>' => '<EMAIL>', '<NAME>' => '<EMAIL>', '<NAME>' => '<EMAIL>' } s.source = { :git => 'https://github.com/kolinkrewinkel/KKGridView.git', :tag => '0.6.8.2' } s.source_files = 'KKGridView' s.clean_paths = 'Examples', 'KKGridView.xcodeproj', 'Resources' s.library = 'stdc++' s.framework = 'QuartzCore' s.requires_arc = true end
promise-J/web-scraper
lib/scraper_instr.rb
class ScraperPlay attr_reader :url def initialize(url) @url = url end def welcome(msg) "#{msg} #{@url}" end def about(msg) msg.to_s end def how_to_go(msg) msg.to_s end def error_input(msg) msg.to_s end def end_scrape(msg) msg end end
promise-J/web-scraper
lib/scraper.rb
require 'nokogiri' require 'open-uri' require_relative './scraper_instr' class Scraper < ScraperPlay attr_reader :url def initialize(url) super @url = url end def fetch_title title_cat = [] first = full_page.css('div#courses .col h3').text second = full_page.css('section#youtube .fa-youtube + h3').text title_cat << first title_cat << second title_cat end def course1 full_page.css('.container-fluid div.row .col-md-4 .bg-black span.font-alt').text end def course2 full_page.css('section#youtube .container .col-md-6 .bg-white span').text.gsub("\n", '') end private def parse_page html = URI.parse(@url).open Nokogiri::HTML(html) end def full_page parse_page.css('body') end end
promise-J/web-scraper
spec/scraper_spec.rb
require_relative '../lib/scraper' require 'nokogiri' require 'open-uri' WEB = Scraper.new('https://www.traversymedia.com/') describe Scraper do describe '#fetch_title' do it 'should fetch the two categories of learning in the traversy media sites' do expect(WEB.fetch_title).to eql(['Popular Udemy Courses | Discount Code [MARCH2021]', 'YouTube Crash Courses']) end end describe '#course1' do it 'should return the list of all the Popular Udemy Courses available in the traversy media sites' do msg1 = 'Modern HTML & CSS From The Beginning50 Projects In 50 DaysReact' msg2 = 'Front To BackBootstrap From ScratchElectron From ScratchMERN Front To Back' expect(WEB.course1).to eql("#{msg1} #{msg2}") end end describe '#course2' do it 'Should return the list of the courses from the from the youtube crash courses.' do expect(WEB.course2).to eql((Nokogiri::HTML(URI.parse('https://www.traversymedia.com/').open)) .css('section#youtube .container .col-md-6 .bg-white span').text.gsub( "\n", '' )) end end end
promise-J/web-scraper
spec/scraper_instr_spec.rb
require_relative '../lib/scraper_instr' SCRAP = ScraperPlay.new('https://www.traversymedia.com/') describe ScraperPlay do describe '#welcome' do it 'should return the message passed as an augument' do expect(SCRAP.welcome('Your selection is invalid, please try again.')) .to eql('Your selection is invalid, please try again. https://www.traversymedia.com/') end end describe '#about' do it 'should return the message passed as an augument' do msg = 'This is the Traversy Media official website. This consist of a whole lots of courses to learn programming.' expect(SCRAP.about(msg)).to eql(msg) end end describe '#how_to_go' do it 'should return the message passed as an augument' do msg = "enter: 1-- To see the list of the categories of courses availabe 2-- To see the list of the most popular web courses 3-- To see the list of all youtube crash courses. another other option would exit." expect(SCRAP.how_to_go(msg)).to eql('enter: 1-- To see the list of the categories of courses availabe 2-- To see the list of the most popular web courses 3-- To see the list of all youtube crash courses. another other option would exit.') end end describe '#error_input' do it 'should return the message passed as an augument' do expect(SCRAP.error_input('Your selection is invalid, please try again.')) .to eql('Your selection is invalid, please try again.') end end describe '#end_scrape' do it 'should return the message passed as an augument' do expect(SCRAP.end_scrape('Scrape ended. Scrape again later')).to eql('Scrape ended. Scrape again later') end end end
promise-J/web-scraper
bin/main.rb
require_relative '../lib/scraper' WEB = Scraper.new('https://www.traversymedia.com/') def getting_started puts WEB.welcome("You are welcomed to web scrapping. Let's scrap") puts 'Are you ready to scrape? ENTER yes or no' choice = gets.chomp return unless choice == 'yes' puts WEB.about('This is The Traversy Media official website. This consist of a whole lots of courses to learn Programming.') puts WEB.how_to_go("enter: 1-- To see the list of the categories of courses availabe 2-- To see the list of the most popular web courses 3-- To see the list of all youtube crash courses. another other option would exit. ") confirm end def confirm ready = true while ready puts 'Choose an option to scrape from the Traversy' scraper_choice = gets.chomp.to_i case scraper_choice when 1 puts WEB.fetch_title when 2 p WEB.course1 when 3 p WEB.course2 else puts WEB.error_input('Your selection is invalid, please try again.') end ready = false end nil end def set_now re_do = true while re_do getting_started puts 'Do you want to scrape again? choose [yes, no]' choice = gets.chomp case choice when 'no' puts 'oooop!!! seem you dont want to scrape again. Lets scrape some other time.' re_do = false puts WEB.end_scrape('Scrape ended. Scrape again later') return when 'yes' getting_started else return end end end set_now
txemagon/pert
lib/pert.rb
require "pert/version" require "pert/node" module Pert def self.process Node.process end def self.load_line(args) return if args.empty? name = args.shift duration = args.pop Node.new(name, duration, args) end def self.print puts Node.dump end end
txemagon/pert
lib/pert/node.rb
<filename>lib/pert/node.rb module Pert class Node @@first_node = nil @@last_node = nil @@node = Hash.new attr_accessor :name, :sooner_time, :last_time, :following, :duration, :previous def initialize(name, duration=0, previous=[]) @previous = [] @following = [] if !@@first_node @@first_node = true @@first_node = Node.new("START") @@last_node = Node.new("END") end @name, @duration = name.upcase, duration.to_i @@node[name] = self previous.each do |node_name| node_name = "START" if node_name == '-' @previous << @@node[node_name] if !node_name.empty? and @@node[node_name] and !@previous.include? @@node[node_name] begin @@node[node_name].following << self unless @@node[node_name].following.include? self rescue puts "#{node_name} not found." end end end def dump() output = Hash.new @following.each do |node| output[" #{self.name} [label=\"{#{@sooner_time} | #{@name} | #{@duration} | #{@last_time}}\"];\n"] = "" output[" #{self.name} -> #{node.name};\n"] = "" output.merge! node.dump end output end def self.dump lines = Hash.new ouput = <<-DIDIGRAPH digraph { rankdir=LR; node [shape=record style=rounded] #{@@first_node.dump.keys.join("") } } DIDIGRAPH end def to_s "#{@name}, [#{(@previous.collect {|p| p.name}).join(', ')}], [#{(@following.collect {|p| p.name}).join(', ')}] #{@duration.to_s} " end def forward_process if @name != "END" and @following.empty? @following << @@last_node @@last_node.previous << self end @sooner_time = @previous.inject(0) do |b,a| begin (a.sooner_time || 0 ) + a.duration > b ? a.sooner_time + a.duration : b rescue 0 end end unless @following.empty? @following.each { |f| f.forward_process } end @sooner_time end def backward_process if !@following or @following.empty? or @name == "END" @last_time = @sooner_time || 0 @following = [] else @last_time = @following.inject(@following[0].last_time) do |b,a| begin a.last_time - a.duration < b ? a.last_time - a.duration : b rescue @@last_node.last_time end end end unless @previous.empty? @previous.each { |p| p.backward_process } end @last_time end def self.process @@first_node.forward_process @@last_node.backward_process end end end
txemagon/pert
pert.gemspec
<reponame>txemagon/pert # -*- encoding: utf-8 -*- require File.expand_path('../lib/pert/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["txemagon"] gem.email = ["<EMAIL>"] gem.description = %q{Creates PERT diagramas using a task file.} gem.summary = %q{Create a task file giving the name of a task, the tasks it depends on and a duration and get the PERT diagram in dot language. } gem.homepage = "" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "pert" gem.require_paths = ["lib"] gem.version = Pert::VERSION gem.add_development_dependency('rdoc') gem.add_development_dependency('aruba') gem.add_development_dependency('rake', '~> 0.9.2') gem.add_dependency('methadone', '~> 1.2.6') end
psparrow/attr-gather
lib/attr/gather/workflow/async_task_executor.rb
<filename>lib/attr/gather/workflow/async_task_executor.rb # frozen_string_literal: true require 'attr/gather/workflow/task_executor' module Attr module Gather module Workflow # @api private class AsyncTaskExecutor < TaskExecutor def initialize(*) super @executor = :io end end end end end
psparrow/attr-gather
lib/attr/gather/filters/contract.rb
# frozen_string_literal: true module Attr module Gather module Filters # Filters values with a dry-validation contract class Contract < Base class IncompatibleContractError < Error; end attr_reader :dry_contract # Creates a new instance of the filter # # @param dry_contract [Dry::Contract] def initialize(dry_contract) validate_dry_contract!(dry_contract) @dry_contract = dry_contract end def call(input) value, filterings = filter_validation_errors input.dup Result.new(value, filterings) end private def filter_validation_errors(unvalidated) contract_result = dry_contract.call(unvalidated) errors = contract_result.errors contract_hash = contract_result.to_h errors.each { |err| filter_error_from_input(err, contract_hash) } filterings = transform_errors_to_filtered_attributes(errors) [contract_hash, filterings] end def filter_error_from_input(error, input) *path, key_to_delete = error.path target = path.empty? ? input : input.dig(*path) target.delete(key_to_delete) end def transform_errors_to_filtered_attributes(errors) errors.map do |err| Filtering.new(err.path, err.text, err.input) end end def validate_dry_contract!(con) return if con.respond_to?(:call) && con.class.respond_to?(:schema) raise IncompatibleContractError, 'contract is not compatible' end end end end end
psparrow/attr-gather
lib/attr/gather/workflow/graphable.rb
# frozen_string_literal: true module Attr module Gather module Workflow # Module containing graph functionality # # @api public module Graphable # Class methods for graph functionality module ClassMethods # Returns the graph of tasks # # @return [TaskGraph] the graph # # @api private def tasks @tasks ||= TaskGraph.new end # Returns a graphviz visualization of the workflow # # @param preview [Boolean] show a preview image of the Workflow # # @api public def to_dot(preview: true) tasks.to_dot(preview: preview) end end # Instance methods for graph functionality module InstanceMethods # Returns a graphviz visualization of the workflow # # @param preview [Boolean] show a preview image of the Workflow # # @api public def to_dot(preview: true) self.class.to_dot(preview: preview) end end def self.included(klass) klass.extend(ClassMethods) klass.include(InstanceMethods) end end end end end
psparrow/attr-gather
spec/shared/test_container.rb
<reponame>psparrow/attr-gather # frozen_string_literal: true require 'dry-validation' RSpec.shared_context 'test container' do let(:test_container) do container = Dry::Container.new container.register(:fetch_from_xml_catalog) do |input| { fetch_from_xml_catalog_ran: input } end container.register(:fetch_from_pim) do |input| { fetch_from_pim_ran: input } end container.register(:tag_from_images) do |input| { tag_from_images_ran: input } end end let(:simple_container) do container = Dry::Container.new container.register(:first) do |_input| { id: :first } end container.register(:second) do |_input| { id: :second } end end let(:simple_workflow_class) do workflow_class = Class.new do include Attr::Gather::Workflow task :first do |t| t.depends_on = [] end task :second do |t| t.depends_on = [] end end workflow_class.container(simple_container) workflow_class end end
psparrow/attr-gather
spec/attr/gather/workflow/task_execution_result_spec.rb
<filename>spec/attr/gather/workflow/task_execution_result_spec.rb # frozen_string_literal: true module Attr module Gather module Workflow # @api private RSpec.describe TaskExecutionResult do describe '#value!' do it 'returns the underlying result value' do result = double(value!: { foo: :bar }) task = instance_double(Task) task_execution_result = described_class.new(task, result) expect(task_execution_result.value!).to eql(foo: :bar) end end describe '#started_at' do it 'returns a time' do result = double(value!: { foo: :bar }) task = instance_double(Task) task_execution_result = described_class.new(task, result) expect(task_execution_result.started_at).to respond_to(:year) end end describe '#uuid' do it 'returns a uuid' do result = double(value!: { foo: :bar }) task = instance_double(Task) task_execution_result = described_class.new(task, result) expect(task_execution_result.uuid).to be_a_uuid end end describe '#state' do it 'uses the result promise state' do result = double(state: :pending) task = instance_double(Task) task_execution_result = described_class.new(task, result) expect(task_execution_result).to have_attributes( state: result.state ) end end describe '#as_json' do it 'is serializable as a hash' do task = Task.new(name: :foobar, depends_on: []) result = Concurrent::Promise.fulfill(Hash[foo: :bar]) task_execution_result = described_class.new(task, result) expect(task_execution_result.as_json).to include( started_at: respond_to(:year), task: { name: :foobar, depends_on: [] }, state: :fulfilled, value: { foo: :bar } ) end end end end end end
psparrow/attr-gather
lib/attr/gather/aggregators/deep_merge.rb
# frozen_string_literal: true require 'attr/gather/aggregators/base' module Attr module Gather module Aggregators # Deep merges result hashes # # @api public class DeepMerge < Base # Initialize a new DeepMerge aggregator # # @param reverse [Boolean] deep merge results in reverse order # # @api private def initialize(reverse: false, **) @reverse = reverse super end def call(input, execution_results) execution_results = execution_results.reverse_each if reverse? result = execution_results.reduce(input.dup) do |memo, res| deep_merge(memo, unwrap_result(res)) end wrap_result(result) end private def reverse? @reverse end def deep_merge(hash, other) Hash[hash].merge(other) do |_, orig, new| if orig.respond_to?(:to_hash) && new.respond_to?(:to_hash) deep_merge(Hash[orig], Hash[new]) else new end end end end end end end
psparrow/attr-gather
spec/attr/gather/filters_spec.rb
<reponame>psparrow/attr-gather<filename>spec/attr/gather/filters_spec.rb # frozen_string_literal: true module Attr module Gather RSpec.describe Filters do describe '.default' do it 'is the :noop filter' do expect(described_class.default).to be_a(Filters::Noop) end end describe '.resolve' do include_context 'user workflow' it 'resolves a named aggregator' do res = described_class.resolve(:contract, user_contract.new) expect(res).to be_a(Filters::Contract) end it 'raises a meaningful error when no aggregator is found' do expect do described_class.resolve(:invalid) end.to raise_error(Registrable::NotFoundError) end end end end end
psparrow/attr-gather
lib/attr/gather/workflow.rb
# frozen_string_literal: true require 'attr/gather/concerns/identifiable' require 'attr/gather/workflow/task' require 'attr/gather/workflow/task_graph' require 'attr/gather/workflow/dsl' require 'attr/gather/workflow/callable' require 'attr/gather/workflow/graphable' module Attr module Gather # Main mixin for functionality. Adds the ability to turn a class into a # workflow. module Workflow # @!parse extend DSL # @!parse include Callable # @!parse extend Graphable::ClassMethods # @!parse include Graphable::InstanceMethods # @!parse include Concerns::Identifiable def self.included(klass) klass.extend(DSL) klass.include(Callable) klass.include(Graphable) klass.include(Concerns::Identifiable) end end end end
psparrow/attr-gather
lib/attr/gather.rb
# frozen_string_literal: true require 'attr/gather/version' module Attr module Gather class Error < StandardError; end # Your code goes here... EMPTY_HASH = {}.freeze end end require 'attr/gather/workflow' require 'attr/gather/aggregators' require 'attr/gather/filters'
psparrow/attr-gather
spec/attr/gather_spec.rb
<filename>spec/attr/gather_spec.rb # frozen_string_literal: true module Attr RSpec.describe Gather do it 'has a version number' do expect(Attr::Gather::VERSION).not_to be nil end end end
psparrow/attr-gather
lib/attr/gather/workflow/task_execution_result.rb
<reponame>psparrow/attr-gather # frozen_string_literal: true module Attr module Gather module Workflow # A wrapper containing information and results of a task execution # # @!attribute [r] started_at # @return [Time] time which the execution occured # # @!attribute [r] task # @return [Attr::Gather::Workflow::Task] task that was run # # @!attribute [r] result # @return [Concurrent::Promise] the result promise of the the task # # @api public TaskExecutionResult = Struct.new(:task, :result) do include Concerns::Identifiable attr_reader :started_at, :uuid def initialize(*) @started_at = Time.now @uuid = SecureRandom.uuid super end # @!attribute [r] state # @return [:unscheduled, :pending, :processing, :rejected, :fulfilled] def state result.state end # Extracts the result, this is an unsafe operation that blocks the # operation, and returns either the value or an exception. # # @note For more information, check out {https://ruby-concurrency.github.io/concurrent-ruby/1.1.5/Concurrent/Concern/Obligation.html#value!-instance_method} def value! result.value! end # Represents the TaskExecutionResult as a hash # # @return [Hash] def as_json value = result.value { started_at: started_at, task: task.as_json, state: state, value: value } end end end end end
psparrow/attr-gather
lib/attr/gather/concerns/registrable.rb
<reponame>psparrow/attr-gather # frozen_string_literal: true module Attr module Gather # Makes a module registrable module Registrable # Error raised when item is already registered class AlreadyRegisteredError < Error; end # Error raised when item is not found class NotFoundError < Attr::Gather::Error; end def self.extended(klass) klass.instance_variable_set(:@__storage__, {}) end # Register item so it can be accessed by name # # @param name [Symbol] name of the item # @yield [options] block to initialize the item def register(name, &blk) name = name.to_sym @__storage__[name] = blk end # Resolve a named item # # @param name [Symbol] # # @return [#call] def resolve(name, *args) block = @__storage__.fetch(name) do raise NotFoundError, "no item with name #{name} registered" end block.call(*args) end # @api private def ensure_name_not_already_registered!(name) return unless @__storage__.key?(name) raise AlreadyRegisteredError, "item with name #{name} already registered" end end end end
psparrow/attr-gather
spec/shared/task_execution_result.rb
<reponame>psparrow/attr-gather # frozen_string_literal: true RSpec.shared_context 'task execution result' do def task_exeution_result(hash) instance_double( Attr::Gather::Workflow::TaskExecutionResult, result: Concurrent::Promise.fulfill(hash) ) end end
psparrow/attr-gather
lib/attr/gather/workflow/callable.rb
# frozen_string_literal: true require 'attr/gather/workflow/task_executor' require 'attr/gather/workflow/async_task_executor' module Attr module Gather module Workflow # @api private module Callable # Execute a workflow # # When executing the workflow, tasks are processed in dependant order, # with the outputs of each batch being fed as inputs to the next batch. # This means the you can enhance the data as the task moves through a # workflow, so later tasks can use the enhanced input data. # # @example # enhancer = MyEnhancingWorkflow.new # enhancer.call(user_id: 1).value! # => {user_id: 1, email: '<EMAIL>} # # @param input [Hash] # # @return [Concurrent::Promise] # # @note For more information, check out {https://dry-rb.org/gems/dry-monads/1.0/result} # # @api public def call(input) final_results = [] tasks = [] each_task_batch.reduce(input.dup) do |aggregated_input, batch| tasks.concat(batch) executor_results = execute_batch(aggregated_input, batch) final_results << executor_results aggregator.call(aggregated_input, executor_results).value! end aggregator.call(input.dup, final_results.flatten(1)) end private # Enumator for task batches # # @return [Enumerator] # # @api private def each_task_batch self.class.tasks.each_batch end # Executes a batch of tasks # # @return [Array<TaskExecutionResult>] # # @api private def execute_batch(aggregated_input, batch) executor = AsyncTaskExecutor.new(batch, container: container) executor.call(aggregated_input) end # @api private def container self.class.container end # @api private def aggregator self.class.aggregator end end end end end
psparrow/attr-gather
lib/attr/gather/workflow/dsl.rb
# frozen_string_literal: true module Attr module Gather module Workflow # DSL for configuring a workflow # # @api public module DSL # Defines a task with name and options # # @param task_name [Symbol] the name of the task # # @example # class EnhanceUserProfile # extend Attr::Gather::Workflow # # # ... # # task :fetch_database_info do |t| # t.depends_on = [] # end # # task :fetch_avatar_info do |t| # t.depends_on = [:fetch_gravatar_info] # end # end # # Calling `task` will yield a task object which you can configure like # a PORO. Tasks will be registered for execution in the workflow. # # @yield [Attr::Gather::Workflow::Task] A task to configure # # @api public def task(task_name, opts = EMPTY_HASH) task = Task.new(name: task_name, **opts) yield task tasks << task self end # Defines a container for task dependencies # # Using a container makes it easy to re-use workflows with different # data sources. Say one workflow was required to use a legacy DB, and # one wanted to use a new DB. Using a container makes it easy to # configure that dependency. # # @example # LegacySystem = Dry::Container.new.tap do |c| # c.register(:database) { Sequel.connect('sqlite://legacy.db') # end # # class EnhanceUserProfile # extend Attr::Gather::Workflow # # container LegacySystem # end # # @param cont [Dry::Container] the Dry::Container to use # # @note For more information, check out {https://dry-rb.org/gems/dry-container} # # @api public def container(cont = nil) @container = cont if cont @container end # Configures the result aggregator # # Aggregators make is possible to build custom logic about # how results should be "merged" together. For example, # yuo could build and aggregator that prioritizes the # values of some tasks over others. # # @example # class EnhanceUserProfile # extend Attr::Gather::Workflow # # aggregator :deep_merge # end # # @param agg [#call] the aggregator to use # # @api public def aggregator(agg = nil, opts = EMPTY_HASH) if agg.nil? && !defined?(@aggregator) @aggregator = Aggregators.default return @aggregator end @aggregator = Aggregators.resolve(agg, filter: filter, **opts) if agg @aggregator end # Defines a filter for filtering out invalid values # # When aggregating data from many sources, it is hard to reason about # all the ways invalid data will be returned. For example, if you are # pulling data from a spreadsheet, there will often be typos, etc. # # Defining a filter allows you to declaratively state what is valid. # attr-gather will use this definition to automatically filter out # invalid values, so they never make it into your system. # # Filtering happens during each step of the workflow, which means that # every Task will receive validated input that you can rely on. # # @example # class UserContract < Dry::Validation::Contract do # params do # optional(:id).filled(:integer) # optional(:email).filled(:str?, format?: /@/) # end # end # # class EnhanceUserProfile # extend Attr::Gather::Workflow # # # Any of the key/value pairs that had validation errors will be # # filtered from the output. # filter :contract, UserContract.new # end # # @param filt [Symbol] the name filter to use # @param args [Array<Object>] arguments for initializing the filter # # @api public def filter(filt = nil, *args) if filt.nil? && !defined?(@filter) @filter = Filters.default return @filter end @filter = Filters.resolve(filt, *args) if filt @filter end end end end end
psparrow/attr-gather
spec/attr/gather/filters/noop_spec.rb
# frozen_string_literal: true require 'attr/gather/filters/noop' module Attr module Gather module Filters RSpec.describe Noop do subject(:noop_filter) { described_class.new } describe '#call' do it 'does not remove any keys' do res = noop_filter.call(test: true) expect(res).to have_attributes(value: { test: true }) end it 'returns a result with no filterings' do res = noop_filter.call(test: true) expect(res).to have_attributes(filterings: []) end end end end end end
psparrow/attr-gather
lib/attr/gather/filters/base.rb
# frozen_string_literal: true module Attr module Gather module Filters # @abstract Subclass and override {#call} to implement # a custom Filter class. class Base # Applies the filter # # @param _input [Hash] # # @return [Attr::Gather::Filter::Result] def call(_input) raise NotImplementedError end end end end end
psparrow/attr-gather
lib/attr/gather/filters/noop.rb
# frozen_string_literal: true module Attr module Gather module Filters # Does not perform any filtering class Noop < Base def call(input) Result.new(input, []) end end end end end
psparrow/attr-gather
lib/attr/gather/workflow/task_graph.rb
# frozen_string_literal: true require 'tsort' require 'attr/gather/workflow/dot_serializer' module Attr module Gather module Workflow # @api private class TaskGraph class UnfinishableError < StandardError; end class InvalidTaskDepedencyError < StandardError; end include TSort attr_reader :tasks_hash def initialize(tasks: []) @tasks_hash = {} tasks.each { |t| self << t } end def <<(task) validate_for_insert!(task) registered_tasks.each do |t| tasks_hash[t] << task if t.depends_on?(task) tasks_hash[t].uniq! end tasks_hash[task] = all_dependencies_for_task(task) end def runnable_tasks tsort.take_while do |task| task.fullfilled_given_remaining_tasks?(registered_tasks) end end def each_batch return enum_for(:each_batch) unless block_given? to_execute = tsort until to_execute.empty? batch = to_execute.take_while do |task| task.fullfilled_given_remaining_tasks?(to_execute) end to_execute -= batch validate_finishable!(batch, to_execute) yield batch end end alias to_a tsort def to_h tasks_hash end def to_dot(preview: false) serializer = DotSerializer.new(self) preview ? serializer.preview : serializer.to_dot end private def tsort_each_child(node, &blk) to_h[node].each(&blk) end def tsort_each_node(&blk) to_h.each_key(&blk) end def validate_finishable!(batch, to_execute) return unless batch.empty? && !to_execute.empty? # TODO: statically verify this raise UnfinishableError, 'task dependencies are not fulfillable' end def validate_for_insert!(task) return if depended_on_tasks_exist?(task) raise InvalidTaskDepedencyError, "could not find a matching task for #{task.name}" end def all_dependencies_for_task(input_task) registered_tasks.select { |task| input_task.depends_on?(task) } end def registered_tasks tasks_hash.keys end def depended_on_tasks_exist?(task) task.depends_on.all? { |t| registered_tasks.map(&:name).include?(t) } end end end end end
psparrow/attr-gather
lib/attr/gather/aggregators/shallow_merge.rb
<filename>lib/attr/gather/aggregators/shallow_merge.rb<gh_stars>0 # frozen_string_literal: true require 'attr/gather/aggregators/base' module Attr module Gather module Aggregators # Shallowly merges results # # @api public class ShallowMerge < Base # Initialize a new DeepMerge aggregator # # @param reverse [Boolean] merge results in reverse order # # @api private def initialize(reverse: false, **) @reverse = reverse super end def call(input, execution_results) items = reverse? ? execution_results.reverse_each : execution_results result = items.reduce(input.dup) do |memo, res| memo.merge(unwrap_result(res)) end wrap_result(result) end private def reverse? @reverse end end end end end
psparrow/attr-gather
lib/attr/gather/aggregators/base.rb
# frozen_string_literal: true module Attr module Gather module Aggregators # @abstract Subclass and override {#call} to implement # a custom Aggregator class. # # @!attribute [r] filter # @return [Attr::Gather::Filters::Base] filter for the output data class Base attr_reader :filter def initialize(**opts) @filter = opts.delete(:filter) end def call(_original_input, _results_array) raise NotImplementedError end private def wrap_result(result) Concurrent::Promise.fulfill(result) end def unwrap_result(res) unvalidated = res.result.value! return unvalidated if filter.nil? filter.call(unvalidated).value end end end end end
psparrow/attr-gather
lib/attr/gather/filters.rb
<filename>lib/attr/gather/filters.rb # frozen_string_literal: true require 'attr/gather/filters/base' require 'attr/gather/filters/result' require 'attr/gather/filters/filtering' require 'attr/gather/concerns/registrable' module Attr module Gather # Namespace for filters module Filters extend Registrable # The default filter if none is specified # # @return [Attr::Gather::Filters::Noop] def self.default @default = resolve(:noop) end register(:contract) do |contract| require 'attr/gather/filters/contract' Contract.new(contract) end register(:noop) do |*| require 'attr/gather/filters/noop' Noop.new end end end end
psparrow/attr-gather
lib/attr/gather/concerns/identifiable.rb
# frozen_string_literal: true require 'securerandom' module Attr module Gather module Concerns # Makes an entity identifiable by adding a #uuid attribute # # @!attribute [r] uuid # @return [String] UUID of the result module Identifiable def initialize(*) @uuid = SecureRandom.uuid super end def self.included(klass) klass.attr_reader(:uuid) end end end end end
psparrow/attr-gather
lib/attr/gather/workflow/task.rb
<gh_stars>0 # frozen_string_literal: true module Attr module Gather module Workflow # @api private class Task attr_accessor :depends_on, :name def initialize(name:, depends_on: []) @name = name @depends_on = depends_on end def depends_on?(other_task) depends_on.include?(other_task.name) end def fullfilled_given_remaining_tasks?(task_list) task_list.none? { |list_task| depends_on?(list_task) } end def as_json { name: name, depends_on: depends_on } end end end end end
psparrow/attr-gather
spec/attr/gather/filters/contract_spec.rb
# frozen_string_literal: true require 'attr/gather/filters/contract' module Attr module Gather module Filters RSpec.describe Contract do subject(:contract_filter) { described_class.new(contract.new) } describe '#call' do let(:contract) do Class.new(Dry::Validation::Contract) do params do optional(:email).filled(:str?, format?: /@/) optional(:country).hash do required(:name).filled(:string) required(:code).filled(:string) end end end end it 'removes keys with errors' do res = contract_filter.call(email: 'bad') expect(res).to have_attributes(value: {}) end it 'removes specific nested keys with errors' do res = contract_filter.call(country: { name: 'test', code: nil }) expect(res).to have_attributes(value: { country: { name: 'test' } }) end it 'returns a list of filter attributes' do res = contract_filter.call(country: { name: 'test', code: nil }) filtered_code = have_attributes( path: %i[country code], reason: 'must be filled', input: nil ) expect(res).to have_attributes(filterings: [filtered_code]) end end describe '.new' do it 'raises when contract class in incompatible' do expect do described_class.new(proc {}) end.to raise_error Contract::IncompatibleContractError end end end end end end