repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
remi/rackbox
|
lib/rackbox/rackbox.rb
|
<filename>lib/rackbox/rackbox.rb
# To add blackbox testing to a Rails app,
# in your spec_helper.rb
#
# require 'rackbox'
#
# Spec::Runner.configure do |config|
# config.use_blackbox = true
# end
#
class RackBox
# i am an rdoc comment on RackBox's eigenclass
class << self
# to turn on some verbosity / logging, set:
# RackBox.verbose = true
attr_accessor :verbose
# A port of Merb's request() method, used in tests
#
# At the moment, we're using #req instead because #request conflicts
# with an existing RSpec-Rails method
#
# Usage:
#
# req '/'
# req login_path
# req url_for(:controller => 'login')
#
# req '/', :method => :post, :params => { 'chunky' => 'bacon' }
#
# req '/', :data => "some XML data to POST"
#
# TODO take any additional options and pass them along to the environment, so we can say
# req '/', :user_agent => 'some custom user agent'
#
def req app_or_request, url = nil, options = {}
puts "RackBox#request url:#{ url.inspect }, options:#{ options.inspect }" if RackBox.verbose
# handle RackBox.request '/foo'
if app_or_request.is_a?(String) && ( url.nil? || url.is_a?(Hash) )
options = url || {}
url = app_or_request
app_or_request = RackBox.app
end
# need to find the request or app
mock_request = nil
if app_or_request.is_a? Rack::MockRequest
mock_request = app_or_request
elsif app_or_request.nil?
if RackBox.app.nil?
raise "Not sure howto to execute a request against app or request: #{ app_or_request.inspect }"
else
mock_request = Rack::MockRequest.new(RackBox.app) # default to RackBox.app if nil
end
elsif app_or_request.respond_to? :call
mock_request = Rack::MockRequest.new(app_or_request)
else
raise "Not sure howto to execute a request against app or request: #{ app_or_request.inspect }"
end
options[:method] ||= ( options[:params] || options[:data] ) ? :post : :get # if params, default to POST, else default to GET
options[:params] ||= { }
if options[:data]
# input should be the data we're likely POSTing ... this overrides any params
input = options[:data]
else
# input should be params, if any
input = RackBox.build_query options[:params]
end
# add HTTP BASIC AUTH support
#
# TODO: DRY this up!
#
if options[:auth]
options[:http_basic_authentication] = options[:auth]
options.delete :auth
end
if options[:basic_auth]
options[:http_basic_authentication] = options[:basic_auth]
options.delete :basic_auth
end
if options[:http_basic_authentication]
username, password = options[:http_basic_authentication]
options.delete :http_basic_authentication
require 'base64'
# for some reason, nase64 encoding adds a \n
encoded_username_and_password = Base64.encode64("#{ username }:#{ password }").sub(/\n$/, '')
options['HTTP_AUTHORIZATION'] = "Basic #{ encoded_username_and_password }"
end
headers = options.dup
headers.delete :data if headers[:data]
headers.delete :params if headers[:params]
headers.delete :method if headers[:method]
# merge input
headers[:input] = input
puts " requesting #{ options[:method].to_s.upcase } #{ url.inspect } #{ headers.inspect }" if RackBox.verbose
mock_request.send options[:method], url, headers
end
alias request req unless defined? request
# the Rack appliction to do 'Black Box' testing against
#
# To set, in your spec_helper.rb or someplace:
# RackBox.app = Rack::Adapter::Rails.new :root => '/root/directory/of/rails/app', :environment => 'test'
#
# If not explicitly set, uses RAILS_ROOT (if defined?) and RAILS_ENV (if defined?)
attr_accessor :app
def app options = { }
unless @app and @app.respond_to?:call
options = {
:silent => false
}.merge(options)
if File.file? 'config.ru'
@app = Rack::Builder.new { eval(File.read('config.ru')) }
elsif defined?RAILS_ENV and defined?RAILS_ROOT
unless defined?Rack::Adapter::Rails
# TODO this is no longer true ... right? does rails < 2.3 work without Thin
puts "You need the Rack::Adapter::Rails to run Rails apps with RackBox." +
" Try: sudo gem install thin" unless options[:silent]
else
@app = Rack::Adapter::Rails.new :root => RAILS_ROOT, :environment => RAILS_ENV
end
elsif File.file?('config/routes.rb') && File.file?('config/environment.rb')
unless defined?Rack::Adapter::Rails
puts "You need the Rack::Adapter::Rails to run Rails apps with RackBox." +
" Try: sudo gem install thin" unless options[:silent]
else
@app = Rack::Adapter::Rails.new :root => '.', :environment => 'development'
end
else
puts "RackBox.app not configured." unless options[:silent]
end
end
@app
end
# helper method for taking a Hash of params and turning them into POST params
#
# >> RackBox.build_query :hello => 'there'
# => 'hello=there'
#
# >> RackBox.build_query :hello => 'there', :foo => 'bar'
# => 'hello=there&foo=bar'
#
# >> RackBox.build_query :user => { :name => 'bob', :password => '<PASSWORD>' }
# => 'user[name]=bob&user[password]=<PASSWORD>'
#
def build_query params_hash = { }
# check to make sure no values are Hashes ...
# if they are, we need to flatten them!
params_hash.each do |key, value|
# params_hash :a => { :b => X, :c => Y }
# needs to be 'a[b]' => X, 'a[b]' => Y
if value.is_a? Hash
inner_hash = params_hash.delete key # { :b => X, :c => Y }
inner_hash.each do |subkey, subvalue|
new_key = "#{ key }[#{ subkey }]" # a[b] or a[c]
puts "warning: overwriting query parameter #{ new_key }" if params_hash[new_key]
params_hash[new_key] = subvalue # 'a[b]' => X or a[c] => Y
end
# we really shouldn't keep going thru the #each now that we've altered data!
return build_query(params_hash)
end
end
Rack::Utils.build_query params_hash
end
end
end
|
remi/rackbox
|
examples/.shared_specs/spec_helper.rb
|
ENV["RAILS_ENV"] = "test"
begin
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
rescue LoadError
# this isn't a rails project
end
require 'spec'
if defined? RAILS_ENV
require 'spec/rails' if defined?RAILS_ENV
end
require File.expand_path(File.dirname(__FILE__) + "/../../../lib/rackbox/spec")
# old way: (i need to create specs to test for backwards compatibility)
# require File.expand_path(File.dirname(__FILE__) + "/../../../lib/rackbox")
# Spec::Runner.configure do |config|
# config.use_blackbox = true
# end
|
remi/rackbox
|
lib/rackbox/spec/configuration.rb
|
# Extend the RSpec configuration class with a use_blackbox option
#
# To add blackbox testing to a Rails app,
# in your spec_helper.rb
#
# require 'rackbox'
#
# Spec::Runner.configure do |config|
# config.use_blackbox = true
# end
#
spec_configuration_class = nil
spec_configuration_class = Spec::Example::Configuration if defined? Spec::Example::Configuration
spec_configuration_class = Spec::Runner::Configuration if defined? Spec::Runner::Configuration
if spec_configuration_class
spec_configuration_class.class_eval do
# Adds blackbox testing to your Rails application using RackBox.
#
# To use, put your 'blackbox' specs into the spec/blackbox
# directory, eg. spec/blackbox/login_spec.rb
#
# In these specs, the RackBox::SpecHelpers#req method will be available to you
#
def use_blackbox= bool
if bool == true
before(:all, :type => :blackbox) do
self.class.instance_eval {
# include our own helpers, eg. RackBox::SpecHelpers#req
include RackBox::SpecHelpers
include RackBox::Matchers
# include generated url methods, eg. login_path.
# default_url_options needs to have a host set for the Urls to work
if defined?ActionController::UrlWriter
include ActionController::UrlWriter
default_url_options[:host] = 'example.com'
end
# if we're not in a Rails app, let's try to load matchers from Webrat
unless defined?RAILS_ENV
begin
require 'webrat'
require 'webrat/core/matchers'
include Webrat::HaveTagMatcher
# include Webrat::HasContent
rescue LoadError
puts "Webrat not available. have_tag & other matchers won't be available. to install, sudo gem install webrat"
end
end
attr_accessor :rackbox_request
}
end
before(:each, :type => :blackbox) do
# i'm sure there's a better way to write this!
#
# i believe metaid would write this as:
# metaclass.class_eval do ... end
#
(class << self; self; end).class_eval do
include RackBox::Matchers
end
@rackbox_request = Rack::MockRequest.new RackBox.app
end
end
end
end
end
|
remi/rackbox
|
spec/rackbox_build_query_spec.rb
|
<filename>spec/rackbox_build_query_spec.rb
require File.dirname(__FILE__) + '/spec_helper'
# add String#unescape to make spec more readable
# 'user[name]=bob' is more readable than 'user%5Bname%5D=bob'
class String
def unescape
Rack::Utils.unescape self
end
end
describe RackBox, 'build_query' do
it 'should support single variable' do
RackBox.build_query( :hello => 'there' ).unescape.should =='hello=there'
end
it 'should support multiple variables' do
result = RackBox.build_query( :hello => 'there', :foo => :bar ).unescape
['hello=there&foo=bar', 'foo=bar&hello=there'].should include(result) # could come in any order!
end
it 'should support inner hashes' do
result = RackBox.build_query( :user => { :name => 'bob', :password => '<PASSWORD>' } ).unescape
result.should include('user[name]=bob')
result.should include('user[password]=<PASSWORD>')
end
it 'should support inner inner inner ... hashes' do
result = RackBox.build_query( :a => { :b => { :c => 'IamC' }, :x => 'xXx' }, :y => 'x' ).unescape
result.should include('a[b][c]=IamC')
result.should include('a[x]=xXx')
result.should include('y=x')
end
end
|
remi/rackbox
|
examples/.shared_specs/blackbox/home_page_spec.rb
|
require File.dirname(__FILE__) + '/../spec_helper'
describe 'Home Page' do
it 'should say something by itself' do
req( '/' ).body.should include('You said nothing')
# this works, but you should probably be careful using
# 'request' and 'response' in Rails specs ... ?
request( '/' ).body.should include('You said nothing')
response = req( '/' )
response.body.should include('You said nothing')
end
it 'should say whatever I tell it to' do
req( '/', :method => :post, :params => { :say => 'hello' } ).body.should include('You said hello')
end
it 'should default to a POST if params are present' do
request('/print-method').body.should == 'get'
request('/print-method', :params => { :hi => 'there' }).body.should == 'post'
request('/print-method', :params => { :hi => 'there' }, :method => :post ).body.should == 'post'
request('/print-method', :params => { :hi => 'there' }, :method => :put ).body.should == 'put'
request('/print-method', :params => { :hi => 'there' }, :method => :get ).body.should == 'get'
end
end
|
remi/rackbox
|
spec/posting_data_spec.rb
|
require File.dirname(__FILE__) + '/spec_helper'
describe RackBox, 'POSTing data' do
before do
@rack_app1 = lambda {|env| [ 200, { }, "you POSTed data: #{ env['rack.input'].read }" ] }
@rack_app2 = lambda {|env|
req = Rack::Request.new env
[ 200, { }, "you POSTed data: #{ req.body.read }" ]
}
@method_app = lambda {|env| [ 200, { }, "method: #{ env['REQUEST_METHOD'] }" ] }
end
it 'should make it easy to POST data, eg. curl -D "XML"' do
RackBox.request(@rack_app1, '/', :data => 'hi there').body.should include('you POSTed data: hi there')
RackBox.request(@rack_app2, '/', :data => 'hi there').body.should include('you POSTed data: hi there')
end
it "should default to POST if method isn't explicitly set and we set :data" do
RackBox.request(@method_app, '/').body.should include('method: GET')
RackBox.request(@method_app, '/', :method => :put).body.should include('method: PUT')
RackBox.request(@method_app, '/', :data => 'hi').body.should include('method: POST')
RackBox.request(@method_app, '/', :data => 'hi', :method => :put).body.should include('method: PUT')
end
it "should default to POST if method isn't explicitly set and we set :params" do
RackBox.request(@method_app, '/').body.should include('method: GET')
RackBox.request(@method_app, '/', :method => :put).body.should include('method: PUT')
RackBox.request(@method_app, '/', :params => { :x => 5 }).body.should include('method: POST')
RackBox.request(@method_app, '/', :params => { :x => 5 }, :method => :put).body.should include('method: PUT')
end
end
|
remi/rackbox
|
lib/rackbox/spec/helpers.rb
|
class RackBox
# Helper methods to include in specs that want to use blackbox testing
#
# TODO For backwards compatibility, I would like to keep a SpecHelpers
# module, but this needs to be renamed because this isn't spec
# specific at all! it needs to be easy to RackBox::App.new(rack_app).request
# or something like that (something generic)
#
# This module has the RackBox::SpecHelpers#request method, which is
# the main method used by RackBox blackbox tests
#
module SpecHelpers
# moved logic into RackBox#request, where it can easily be re-used
def req url, options = {}
RackBox.request @rackbox_request, url, options
end
alias request req unless defined? request
end
end
|
remi/rackbox
|
spec/request_method_spec.rb
|
<gh_stars>1-10
require File.dirname(__FILE__) + '/spec_helper'
describe RackBox, '#request' do
before do
@rack_app = lambda {|env| [ 200, { }, "you requested path #{ env['PATH_INFO'] }" ] }
end
it 'should be easy to run the #request method against any Rack app' do
RackBox::App.new(@rack_app).request('/hello').body.should include('you requested path /hello')
end
it 'should be even easier to run the #request method against any Rack app' do
RackBox.request(@rack_app, '/hello').body.should include('you requested path /hello')
end
it "should default to using RackBox.app if an app isn't passed" do
lambda { RackBox.request('/hello') }.should raise_error
RackBox.app = @rack_app
RackBox.request('/hello').body.should include('you requested path /hello')
end
end
|
remi/rackbox
|
rails_generators/blackbox_spec/blackbox_spec_generator.rb
|
<gh_stars>1-10
# This generator creates a new 'blackbox' spec, using RackBox
class BlackboxSpecGenerator < Rails::Generator::Base
attr_accessor :name_of_spec_to_create, :name_of_spec_file_to_create
# `./script/generate blackbox_spec foo` will result in:
#
# runtime_args: ['foo']
# runtime_options: {:quiet=>false, :generator=>"blackbox_spec", :command=>:create, :collision=>:ask}
#
def initialize(runtime_args, runtime_options = {})
setup_rails_to_run_blackbox_specs
@name_of_spec_to_create = runtime_args.join(' ')
@name_of_spec_file_to_create = runtime_args.join('_').downcase
super
end
# this should be done by ./script/generate blackbox
def setup_rails_to_run_blackbox_specs
spec_helper = File.join RAILS_ROOT, 'spec', 'spec_helper.rb'
updated = false
if File.file? spec_helper
source = File.read spec_helper
unless source =~ /require .rackbox./
if source =~ /require .spec\/rails./
source.sub!(/require .spec\/rails./, "\\0\nrequire 'rackbox'") # inject a "require 'rackbox'" statement
updated = true
end
end
unless source =~ /config.use_blackbox/
if source =~ /.configure do \|config\|/
source.sub!(/.configure do \|config\|/, "\\0\n config.use_blackbox = true") # inject config.use_blackbox
updated = true
end
end
if updated
File.open(spec_helper, 'w'){|f| f << source }
puts " updated spec/spec_helper.rb"
end
end
end
def manifest
record do |m|
m.directory 'spec/blackbox'
m.template 'spec.erb', "spec/blackbox/#{ name_of_spec_file_to_create }_spec.rb" # what can i call to get args???
end
end
protected
def banner
"Usage: #{$0} blackbox_spec Name of Spec to Create"
end
end
|
remi/rackbox
|
examples/rails/config/routes.rb
|
ActionController::Routing::Routes.draw do |map|
map.print_method 'print-method', :controller => 'welcome', :action => 'print_method'
map.print_session 'print-session', :controller => 'welcome', :action => 'print_session'
map.redirect 'redirect', :controller => 'welcome', :action => 'redirect'
map.some_text 'some_text', :controller => 'welcome', :action => 'some_text'
map.some_html 'some_html', :controller => 'welcome', :action => 'some_html'
map.relative 'relative', :controller => 'welcome', :action => 'relative'
map.root :controller => 'welcome'
end
|
jasonkolodziej/dms
|
app/controllers/forms_controller.rb
|
<gh_stars>1-10
class FormsController < ApplicationController
def general
@page_title = 'Forms_General'
end
def advanced
@page_title = 'Forms_Advanced'
end
def editors
@page_title = 'Forms_Editors'
end
end
|
jasonkolodziej/dms
|
app/controllers/tables_controller.rb
|
<reponame>jasonkolodziej/dms
class TablesController < ApplicationController
def simple
@page_title = 'Tables_Simple'
end
def data
@page_title = 'Tables_Data'
end
end
|
jasonkolodziej/dms
|
app/controllers/calendar_controller.rb
|
<reponame>jasonkolodziej/dms
class CalendarController < ApplicationController
def index
@page_title = 'Calendar'
end
end
|
jasonkolodziej/dms
|
config/initializers/assets.rb
|
<filename>config/initializers/assets.rb
# 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( dashboard_v1.css dashboard_v1.js )
Rails.application.config.assets.precompile += %w( dashboard_v2.css dashboard_v2.js )
Rails.application.config.assets.precompile += %w( widgets.css widgets.js )
Rails.application.config.assets.precompile += %w( charts_chartjs.css charts_chartjs.js )
Rails.application.config.assets.precompile += %w( charts_morris.css charts_morris.js )
Rails.application.config.assets.precompile += %w( charts_flot.css charts_flot.js )
Rails.application.config.assets.precompile += %w( charts_inline.css charts_inline.js )
Rails.application.config.assets.precompile += %w( uielements_general.css uielements_general.js )
Rails.application.config.assets.precompile += %w( uielements_icons.css uielements_icons.js )
Rails.application.config.assets.precompile += %w( uielements_buttons.css uielements_buttons.js )
Rails.application.config.assets.precompile += %w( uielements_sliders.css uielements_sliders.js )
Rails.application.config.assets.precompile += %w( uielements_timeline.css uielements_timeline.js )
Rails.application.config.assets.precompile += %w( uielements_modals.css uielements_modals.js )
Rails.application.config.assets.precompile += %w( forms_general.css forms_general.js )
Rails.application.config.assets.precompile += %w( forms_advanced.css forms_advanced.js )
Rails.application.config.assets.precompile += %w( forms_editors.css forms_editors.js )
Rails.application.config.assets.precompile += %w( tables_simple.css tables_simple.js )
Rails.application.config.assets.precompile += %w( tables_data.css tables_data.js )
Rails.application.config.assets.precompile += %w( calendar.css calendar.js )
Rails.application.config.assets.precompile += %w( mailbox_inbox.css mailbox_inbox.js )
Rails.application.config.assets.precompile += %w( mailbox_compose.css mailbox_compose.js )
Rails.application.config.assets.precompile += %w( mailbox_read.css mailbox_read.js )
Rails.application.config.assets.precompile += %w( examples_invoice.css examples_invoice.js )
Rails.application.config.assets.precompile += %w( examples_invoice_print.css )
Rails.application.config.assets.precompile += %w( examples_profile.css examples_profile.js )
Rails.application.config.assets.precompile += %w( examples_login.css examples_login.js )
Rails.application.config.assets.precompile += %w( examples_register.css examples_register.js )
Rails.application.config.assets.precompile += %w( examples_lockscreen.css examples_lockscreen.js )
Rails.application.config.assets.precompile += %w( examples_error_404.css examples_error_404.js )
Rails.application.config.assets.precompile += %w( examples_error_500.css examples_error_500.js )
Rails.application.config.assets.precompile += %w( examples_blank.css examples_blank.js )
Rails.application.config.assets.precompile += %w( examples_pace.css examples_pace.js )
|
jasonkolodziej/dms
|
app/controllers/widgets_controller.rb
|
<reponame>jasonkolodziej/dms
class WidgetsController < ApplicationController
def index
@page_title = 'Widgets'
end
end
|
jasonkolodziej/dms
|
app/controllers/dashboard_controller.rb
|
<filename>app/controllers/dashboard_controller.rb<gh_stars>0
class DashboardController < ApplicationController
def version1
@page_title = 'Dashboard v1'
end
def version2
@page_title = 'Dashboard v2'
end
end
|
jasonkolodziej/dms
|
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
before_action :get_adminlte_config
private
# -Please configure AdminLTE in the AdminLteConfig class and do not change this function
# -This function is only used as an intermediate function to get the config settings and transfer them
# to the layout as instance variables
def get_adminlte_config
alc = AdminLteConfig.new
# If this setting is on, none of the settings that you configured are going to be used
# Please turn this off through the AdminLteConfig class before seeing your changed in effect
@demo_mode = alc.demo_mode
@layout = alc.layout
@top_nav = alc.top_nav
@sidebar = alc.sidebar
@collapsed_sidebar_expand_on_hover = alc.collapsed_sidebar_expand_on_hover
@right_sidebar_slide = alc.right_sidebar_slide
@right_sidebar_skin = alc.right_sidebar_skin
@skin = alc.skin
end
class AdminLteConfig
def initialize
# -This setting runs the demo features to demo the application for you to decide the configuration settings that you
# want to use in the production environment.
# -Please configure the application by using the below settings after demoing the application
# -Please be cautious that the application won't configure the application with your settings
# if you do not turn off this setting first!!!
@demo_mode = true
# The layout setting specifies how the layout is going to be configured
# Set this to one of the below settings
# '' -> this is the default setting
# 'fixed' -> this makes the sidebars scrollable
# 'boxed' -> this makes the dashboard smaller in boxed view with a stylish background
@layout = ''
# If this setting is on, all the sidebars get disabled and the navigation gets moved to the top navigation bar
# If this setting is enabled, none of the below sidebar settings will be concerned
# Default value is false
@top_nav_only = false
# This setting collapses the sidebar if it is true
# Default value is false
@collapsed_sidebar = false
# This setting will automatically turn on the @collapsed_sidebar setting
# The sidebar automatically expands if a user hovers on it if this setting is on
# Default value is false
@collapsed_sidebar_expand_on_hover = false
# Slides the main content to the left if the right control sidebar is opened
# Default value for this setting is false
@right_sidebar_slide = false
# This changes the color of the control sidebar to a light skin color
# Default value for this setting is false
@right_sidebar_skin_light = false
# Pick a skin color for AdminLTE from the below list
# Default skin color is green
# 'skin-blue',
# 'skin-black',
# 'skin-red',
# 'skin-yellow',
# 'skin-purple',
# 'skin-green',
# 'skin-blue-light',
# 'skin-black-light',
# 'skin-red-light',
# 'skin-yellow-light',
# 'skin-purple-light',
# 'skin-green-light'
@skin = 'skin-black'
@page_title = 'Donor Management System'
end
# reader methods for the class variables
def page_title
@page_title
end
def demo_mode
@demo_mode
end
def layout
if @layout == 'fixed'
'fixed'
elsif @layout == 'boxed'
'layout-boxed'
else
''
end
end
def top_nav
if @top_nav_only
'layout-top-nav'
else
''
end
end
def sidebar
if !@top_nav_only && @collapsed_sidebar
'sidebar-collapse'
else
''
end
end
def collapsed_sidebar_expand_on_hover
!@top_nav_only && @collapsed_sidebar_expand_on_hover
end
def right_sidebar_slide
!@top_nav_only && @right_sidebar_slide
end
def right_sidebar_skin
if !@top_nav_only && @right_sidebar_skin_light
'control-sidebar-light'
else
'control-sidebar-dark'
end
end
def skin
@skin
end
end
end
|
jasonkolodziej/dms
|
app/controllers/examples_controller.rb
|
class ExamplesController < ApplicationController
def invoice
@page_title = 'Invoice'
end
def invoice_print
@page_title = 'Invoice'
render :layout => false
end
def profile
@page_title = 'Profile'
end
def login
@page_title = 'Login'
render :layout => false
end
def register
@page_title = 'Register'
render :layout => false
end
def lockscreen
@page_title = 'Lockscreen'
render :layout => false
end
def error_404
@page_title = '404 Error'
end
def error_500
@page_title = '500 Error'
end
def blank
@page_title = 'Blank Page'
end
def pace
@page_title = 'Pace Page'
end
end
|
jasonkolodziej/dms
|
app/controllers/mailbox_controller.rb
|
<reponame>jasonkolodziej/dms
class MailboxController < ApplicationController
def inbox
@page_title = 'Mailbox_Inbox'
end
def compose
@page_title = 'Mailbox_Compose'
end
def read
@page_title = 'Mailbox_Read'
end
end
|
jasonkolodziej/dms
|
app/controllers/charts_controller.rb
|
class ChartsController < ApplicationController
def chartjs
@page_title = 'Charts_ChartJS'
end
def morris
@page_title = 'Charts_Morris'
end
def flot
@page_title = 'Charts_Flot'
end
def inline
@page_title = 'Charts_Inline'
end
end
|
jasonkolodziej/dms
|
app/controllers/uielements_controller.rb
|
<gh_stars>1-10
class UielementsController < ApplicationController
def general
@page_title = 'UI_Elements_General'
end
def icons
@page_title = 'UI_Elements_Icons'
end
def buttons
@page_title = 'UI_Elements_Buttons'
end
def sliders
@page_title = 'UI_Elements_Sliders'
end
def timeline
@page_title = 'UI_Elements_Timeline'
end
def modals
@page_title = 'UI_Elements_Modals'
end
end
|
MattMencel/ruby-sysaid
|
lib/sysaid/user.rb
|
class SysAid::User
attr_accessor :username, :display_name, :email, :phone, :first_name, :last_name, :admin, :agreement, :building,
:car_number, :cellphone, :company, :cubic, :cust_int1, :cust_int2, :cust_list1, :cust_list2, :cust_notes,
:cust_text1, :cust_text2, :department, :disable, :email_notifications, :enable_login_to_eup, :floor, :location,
:manager, :notes, :sms, :user_manager_name, :login_domain, :login_user, :secondary_email
# Creates a SysAid::User object
#
# Example:
# >> SysAid::User.new
# => SysAid::User
#
# Arguments:
# username: (SysAid username, optional)
def initialize(username = nil)
self.username = username
self.email_notifications = true
end
def self.find_by_username(username)
user = SysAid::User.new(username)
return nil unless user.refresh
return user
end
# Loads the latest user information from the SysAid server
def refresh
SysAid.ensure_logged_in
response = SysAid.call(:load_by_string_id, message: to_xml.to_s )
if response.to_hash[:load_by_string_id_response][:return]
set_self_from_response(response.to_hash[:load_by_string_id_response][:return])
return true
end
return false
end
# Saves a user back to the SysAid server
#
# Example:
# >> user_object.save
# => true
def save
SysAid.ensure_logged_in
# Save it via the SOAP API
response = SysAid.call(:save, message: to_xml(false).to_s )
if response.to_hash[:save_response][:return]
return true
else
return false
end
end
# Deletes a user from the SysAid server
#
# Example:
# >> user_object.delete
# => nil
def delete
SysAid.ensure_logged_in
SysAid.call(:delete, message: to_xml(false).to_s )
end
private
def to_xml(include_id = true)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiSysAidUser") { |b|
b.admin(self.admin, 'xsi:type' => 'xsd:boolean')
b.agreement(self.agreement, 'xsi:type' => 'xsd:int')
b.building(self.building, 'xsi:type' => 'xsd:string')
b.carNumber(self.car_number, 'xsi:type' => 'xsd:string')
b.cellphone(self.cellphone, 'xsi:type' => 'xsd:string')
b.company(self.company, 'xsi:type' => 'xsd:int')
b.cubic(self.cubic, 'xsi:type' => 'xsd:string')
b.custInt1(self.cust_int1, 'xsi:type' => 'xsd:int')
b.custInt2(self.cust_int2, 'xsi:type' => 'xsd:int')
b.custList1(self.cust_list1, 'xsi:type' => 'xsd:int')
b.custList2(self.cust_list2, 'xsi:type' => 'xsd:int')
b.custNotes(self.cust_notes, 'xsi:type' => 'xsd:string')
b.custText1(self.cust_text1, 'xsi:type' => 'xsd:string')
b.custText2(self.cust_text2, 'xsi:type' => 'xsd:string')
b.customDateFields
b.customFields
b.department(self.department, 'xsi:type' => 'xsd:int')
b.disable(self.disable, 'xsi:type' => 'xsd:boolean')
b.displayName(self.display_name, 'xsi:type' => 'xsd:string')
b.email(self.email, 'xsi:type' => 'xsd:string')
b.emailNotifications(self.email_notifications, 'xsi:type' => 'xsd:boolean')
b.enableLoginToEup(self.enable_login_to_eup, 'xsi:type' => 'xsd:boolean')
b.firstName(self.first_name, 'xsi:type' => 'xsd:string')
b.floor(self.floor, 'xsi:type' => 'xsd:string')
b.lastName(self.last_name, 'xsi:type' => 'xsd:string')
b.location(self.location, 'xsi:type' => 'xsd:int')
b.loginDomain(self.login_domain, 'xsi:type' => 'xsd:string')
b.loginUser(self.login_user, 'xsi:type' => 'xsd:string')
b.manager(self.manager, 'xsi:type' => 'xsd:boolean')
b.notes(self.notes, 'xsi:type' => 'xsd:string')
b.phone(self.phone, 'xsi:type' => 'xsd:string')
b.secondaryEmail(self.secondary_email, 'xsi:type' => 'xsd:string')
b.sms(self.sms, 'xsi:type' => 'xsd:string')
b.userManagerName(self.user_manager_name, 'xsi:type' => 'xsd:string')
b.userName(self.username, 'xsi:type' => 'xsd:string')
}
xml = builder.id(self.username) if include_id
xml
end
# Update instance variables to match what is in response
def set_self_from_response(response)
self.username = response[:user_name]
self.display_name = response[:display_name]
self.email = response[:email]
self.phone = response[:phone]
self.first_name = response[:first_name]
self.last_name = response[:last_name]
self.admin = response[:admin]
self.agreement = response[:agreement]
self.building = response[:building]
self.car_number = response[:car_number]
self.cellphone = response[:cellphone]
self.company = response[:company]
self.cubic = response[:cubic]
self.cust_int1 = response[:cust_int1]
self.cust_int2 = response[:cust_int2]
self.cust_list1 = response[:cust_list1]
self.cust_list2 = response[:cust_list2]
self.cust_notes = response[:cust_notes]
self.cust_text1 = response[:cust_text1]
self.cust_text2 = response[:cust_text2]
self.department = response[:department]
self.disable = response[:disable]
self.email_notifications = response[:email_notifications]
self.enable_login_to_eup = response[:enableLoginToEup]
self.floor = response[:floor]
self.location = response[:location]
self.manager = response[:manager]
self.notes = response[:notes]
self.sms = response[:sms]
self.user_manager_name = response[:userManagerName]
self.login_domain = response[:login_domain]
self.login_user = response[:login_user]
self.secondary_email = response[:secondaryEmail]
end
end
|
MattMencel/ruby-sysaid
|
lib/sysaid/ticket.rb
|
<filename>lib/sysaid/ticket.rb<gh_stars>0
require 'date'
class SysAid::Ticket
attr_accessor :agreement, :assign_counter, :assigned_to, :ciid, :category, :current_support_level, :cust_int1,
:cust_int2, :cust_list1, :cust_list2, :description, :escalation, :id, :location, :max_support_level,
:parent_link, :priority, :project_id, :reopen_counter, :request_user, :source, :sr_sub_type, :sr_type,
:status, :sub_category, :submit_user, :success_rating, :task_id, :title, :urgency, :version, :archive,
:assigned_group, :cc, :change_category, :close_time, :closure_information, :computer_id,
:cust_notes, :cust_text1, :cust_text2, :impact, :notes, :resolution, :solution, :third_level_category,
:update_time, :update_user, :user_manager, :workaround, :insert_time, :followup_text, :email_account
def initialize
reset_all_attributes
end
# Needed by both initialize and delete (to empty out the object when deleted)
def reset_all_attributes
self.agreement = nil
self.archive = nil
self.assign_counter = nil
self.assigned_group = nil
self.assigned_to = nil
self.ciid = nil
self.category = nil
self.cc = nil
self.change_category = nil
self.close_time = Date.new
self.closure_information = nil
self.computer_id = nil
self.current_support_level = nil
self.cust_int1 = nil
self.cust_int2 = nil
self.cust_list1 = nil
self.cust_list2 = nil
self.cust_notes = nil
self.cust_text1 = nil
self.cust_text2 = nil
self.description = nil
self.email_account = nil
self.escalation = nil
self.followup_text = nil
self.id = nil
self.impact = nil
self.insert_time = Date.new
self.location = nil
self.max_support_level = nil
self.notes = nil
self.parent_link = nil
self.priority = nil
self.project_id = nil
self.reopen_counter = nil
self.request_user = nil
self.resolution = nil
self.solution = nil
self.source = nil
self.sr_sub_type = nil
self.sr_type = nil
self.status = nil
self.sub_category = nil
self.success_rating = nil
self.task_id = nil
self.third_level_category = nil
self.title = nil
self.update_time = Date.new
self.update_user = nil
self.urgency = nil
self.user_manager = nil
self.version = nil
self.workaround = nil
end
def self.find_by_id(ticket_id)
ticket = SysAid::Ticket.new
ticket.id = ticket_id
return nil unless ticket.refresh
return ticket
end
def self.find_by_query(query)
SysAid.ensure_logged_in
response = SysAid.call(:execute_select_query, message: sql_query(query))
if response.to_hash[:execute_select_query_response][:return]
return response.to_hash[:execute_select_query_response][:return]
end
return false
end
# Loads the latest ticket information from the SysAid server
def refresh
SysAid.ensure_logged_in
response = SysAid.call(:load_by_string_id, message: to_xml)
if response.to_hash[:load_by_string_id_response][:return]
set_self_from_response(response.to_hash[:load_by_string_id_response][:return])
return true
end
return false
end
# Though the 'notes' field is merely an editable string, 'add_note'
# mimics the behavior of the SysAid web client.
def add_note(user, note, time = Time.now)
# NOTE: Notes are prepended.
new_note = "#{user} (#{time.strftime("%-m/%-d/%y %I:%M %p")}):\n #{note}"
if self.notes
self.notes = new_note + "\n=============================\n" + self.notes
else
self.notes = new_note
end
end
# Saves a ticket back to the SysAid server
#
# Example:
# >> ticket_object.save
# => true
def save
SysAid.ensure_logged_in
# Save it via the SOAP API
response = SysAid.call(:save, message: to_xml(false))
if response.to_hash[:save_response][:return]
# In the case of a new ticket, the SysAid response will be the assigned ID
self.id = response.to_hash[:save_response][:return] unless self.id
return true
else
return false
end
end
# Deletes a ticket from the SysAid server
#
# No return value as SysAid's 'delete' call returns void. No idea why.
#
# Example:
# >> ticket_object.delete
# => true
def delete
SysAid.ensure_logged_in
SysAid.call(:delete, message: to_xml(false))
reset_all_attributes
end
private
def self.sql_query(query)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiTicket")
xml = builder.condition(query)
xml
end
def to_xml(include_id = true)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiServiceRequest") { |b|
b.agreement(self.agreement, 'xsi:type' => 'xsd:int')
b.archive(self.archive, 'xsi:type' => 'xsd:boolean')
b.assignCounter(self.assign_counter, 'xsi:type' => 'xsd:int')
b.assignedGroup(self.assigned_group, 'xsi:type' => 'xsd:string')
b.assignedTo(self.assigned_to, 'xsi:type' => 'xsd:string')
b.CIId(self.ciid, 'xsi:type' => 'xsd:int')
b.category(self.category, 'xsi:type' => 'xsd:string')
b.cc(self.cc, 'xsi:type' => 'xsd:string')
b.changeCategory(self.change_category, 'xsi:type' => 'xsd:int')
b.closeTime(self.close_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.closureInformation(self.closure_information, 'xsi:type' => 'xsd:int')
b.computerID(self.computer_id, 'xsi:type' => 'xsd:string')
b.currentSupportLevel(self.current_support_level, 'xsi:type' => 'xsd:int')
b.custInt1(self.cust_int1, 'xsi:type' => 'xsd:int')
b.custInt2(self.cust_int2, 'xsi:type' => 'xsd:int')
b.custList1(self.cust_list1, 'xsi:type' => 'xsd:int')
b.custList2(self.cust_list2, 'xsi:type' => 'xsd:int')
b.custNotes(self.cust_notes, 'xsi:type' => 'xsd:string')
b.custText1(self.cust_text1, 'xsi:type' => 'xsd:string')
b.custText2(self.cust_text2, 'xsi:type' => 'xsd:string')
b.customDateFields
#b.customFields
b.description(self.description, 'xsi:type' => 'xsd:string')
b.emailAccount(self.email_account, 'xsi:type' => 'xsd:string')
b.escalation(self.escalation, 'xsi:type' => 'xsd:int')
b.followupText(self.followup_text, 'xsi:type' => 'xsd:string')
b.id(self.id, 'xsi:type' => 'xsd:int')
b.impact(self.impact, 'xsi:type' => 'xsd:int')
b.insertTime(self.insert_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.location(self.location, 'xsi:type' => 'xsd:int')
b.maxSupportLevel(self.max_support_level, 'xsi:type' => 'xsd:int')
b.notes(self.notes, 'xsi:type' => 'xsd:string')
b.parentLink(self.parent_link, 'xsi:type' => 'xsd:int')
b.priority(self.priority, 'xsi:type' => 'xsd:int')
b.projectID(self.project_id, 'xsi:type' => 'xsd:int')
b.reopenCounter(self.reopen_counter, 'xsi:type' => 'xsd:int')
b.requestUser(self.request_user, 'xsi:type' => 'xsd:string')
b.resolution(self.resolution, 'xsi:type' => 'xsd:string')
b.solution(self.solution, 'xsi:type' => 'xsd:string')
b.source(self.source, 'xsi:type' => 'xsd:int')
b.srSubType(self.sr_sub_type, 'xsi:type' => 'xsd:int')
b.srType(self.sr_type, 'xsi:type' => 'xsd:int')
b.status(self.status, 'xsi:type' => 'xsd:int')
b.subCategory(self.sub_category, 'xsi:type' => 'xsd:string')
b.successRating(self.success_rating, 'xsi:type' => 'xsd:int')
b.taskID(self.task_id, 'xsi:type' => 'xsd:int')
b.thirdLevelCategory(self.third_level_category, 'xsi:type' => 'xsd:string')
b.title(self.title, 'xsi:type' => 'xsd:string')
b.updateTime(self.update_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.updateUser(self.update_user, 'xsi:type' => 'xsd:string')
b.urgency(self.urgency, 'xsi:type' => 'xsd:int')
b.userManager(self.user_manager, 'xsi:type' => 'xsd:string')
b.version(self.version, 'xsi:type' => 'xsd:int')
b.workaround(self.workaround, 'xsi:type' => 'xsd:string')
}
xml = builder.id(self.id) if include_id
xml
end
# Update instance variables to match what is in response
def set_self_from_response(response)
self.agreement = response[:agreement]
self.archive = response[:archive]
self.assign_counter = response[:assign_counter]
self.assigned_group = response[:assign_group]
self.assigned_to = response[:assign_to]
self.ciid = response[:ci_id]
self.category = response[:category]
self.cc = response[:cc]
self.change_category = response[:change_category]
self.close_time = response[:close_time] if response[:close_time]
self.closure_information = response[:closure_information]
self.computer_id = response[:computer_id]
self.current_support_level = response[:current_support_level]
self.cust_int1 = response[:cust_int1]
self.cust_int2 = response[:cust_int2]
self.cust_list1 = response[:cust_list1]
self.cust_list2 = response[:cust_list2]
self.cust_notes = response[:cust_notes]
self.cust_text1 = response[:cust_text1]
self.cust_text2 = response[:cust_text2]
self.description = response[:description]
self.email_account = response[:email_account]
self.escalation = response[:escalation]
self.followup_text = response[:followup_text]
self.id = response[:id]
self.impact = response[:impact]
self.insert_time = response[:insert_time]
self.location = response[:location]
self.max_support_level = response[:max_support_level]
self.notes = response[:notes]
self.parent_link = response[:parent_link]
self.priority = response[:priority]
self.project_id = response[:project_id]
self.reopen_counter = response[:reopen_counter]
self.request_user = response[:request_user]
self.resolution = response[:resolution]
self.solution = response[:solution]
self.source = response[:source]
self.sr_sub_type = response[:sr_sub_type]
self.sr_type = response[:sr_type]
self.status = response[:status]
self.sub_category = response[:sub_category]
self.success_rating = response[:success_rating]
self.task_id = response[:task_id]
self.third_level_category = response[:third_level_category]
self.title = response[:title]
self.update_time = response[:update_time]
self.update_user = response[:update_user]
self.urgency = response[:urgency]
self.user_manager = response[:user_manager]
self.version = response[:version]
self.workaround = response[:workaround]
end
end
|
MattMencel/ruby-sysaid
|
sysaid.gemspec
|
<reponame>MattMencel/ruby-sysaid<gh_stars>0
Gem::Specification.new do |s|
s.name = 'sysaid'
s.version = '0.3.5'
s.date = '2015-12-07'
s.summary = "ruby-sysaid"
s.description = "Wrapper for the SysAid SOAP API"
s.authors = ["<NAME>"]
s.email = '<EMAIL>'
s.license = 'MIT'
s.files = Dir["lib/sysaid.rb"] + Dir["lib/sysaid/*.rb"]
s.homepage =
'https://github.com/cthielen/ruby-sysaid'
s.add_runtime_dependency 'savon', '~> 2.3', '>= 2.3.0'
end
|
MattMencel/ruby-sysaid
|
lib/sysaid/task.rb
|
require 'date'
class SysAid::Task
attr_accessor :category, :ciid, :cust_date1, :cust_date2, :cust_int1, :cust_int2, :cust_list1, :cust_list2,
:cust_notes, :custom_date_fields, :custom_fields, :cust_text1, :cust_text2, :description,
:end_time, :estimation, :id, :notes, :progress, :project_id, :start_time, :status,
:task_dependency, :task_dependency_type, :title, :version
def initialize
self.start_time = Date.new
self.end_time = Date.new
end
def self.find_by_id(task_id)
task = SysAid::Task.new
task.id = task_id
return nil unless task.refresh
return task
end
def self.find_by_project_id(project_id)
SysAid.ensure_logged_in
response = SysAid.call(:execute_select_query, message: sql_query(project_id))
if response.to_hash[:execute_select_query_response][:return]
return response.to_hash[:execute_select_query_response][:return]
end
return false
end
# Loads the latest task information from the SysAid server
def refresh
SysAid.ensure_logged_in
response = SysAid.call(:load_by_string_id, message: to_xml)
if response.to_hash[:load_by_string_id_response][:return]
set_self_from_response(response.to_hash[:load_by_string_id_response][:return])
return true
end
return false
end
# Saves a task back to the SysAid server
#
# Example:
# >> task_object.save
# => true
def save
SysAid.ensure_logged_in
# Save it via the SOAP API
response = SysAid.call(:save, message: to_xml(false))
if response.to_hash[:save_response][:return]
return true
else
return false
end
end
# Deletes a task from the SysAid server
#
# No return value as SysAid's 'delete' call returns void. No idea why.
#
# Example:
# >> task_object.delete
# => true
def delete
SysAid.ensure_logged_in
SysAid.call(:delete, message: to_xml(false))
end
private
def self.sql_query(project_id)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiTask")
xml = builder.condition("project_id=#{project_id}")
xml
end
def to_xml(include_id = true)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiTask") { |b|
b.category(self.category, 'xsi:type' => 'xsd:int')
b.ciId(self.ciid, 'xsi:type' => 'xsd:int')
#b.custDate1(self.cust_date1.rfc3339, 'xsi:type' => 'xsd:dateTime')
#b.custDate2(self.cust_date2.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.custInt1(self.cust_int1, 'xsi:type' => 'xsd:int')
b.custInt2(self.cust_int2, 'xsi:type' => 'xsd:int')
b.custList1(self.cust_list1, 'xsi:type' => 'xsd:int')
b.custList2(self.cust_list2, 'xsi:type' => 'xsd:int')
b.custNotes(self.cust_notes, 'xsi:type' => 'xsd:string')
b.custText1(self.cust_text1, 'xsi:type' => 'xsd:string')
b.custText2(self.cust_text2, 'xsi:type' => 'xsd:string')
b.customDateFields
#b.customFields
b.description(self.description, 'xsi:type' => 'xsd:string')
b.endTime(self.end_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.estimation(self.estimation, 'xsi:type' => 'xsd:int')
b.id(self.id, 'xsi:type' => 'xsd:int')
b.notes(self.notes, 'xsi:type' => 'xsd:string')
b.progress(self.progress, 'xsi:type' => 'xsd:int')
b.projectId(self.project_id, 'xsi:type' => 'xsd:int')
b.startTime(self.start_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.status(self.status, 'xsi:type' => 'xsd:int')
b.taskDependency(self.task_dependency, 'xsi:type' => 'xsd:int')
b.taskDependencyType(self.task_dependency_type, 'xsi:type' => 'xsd:int')
b.title(self.title, 'xsi:type' => 'xsd:string')
b.version(self.version, 'xsi:type' => 'xsd:int')
}
xml = builder.id(self.id) if include_id
xml
end
# Update instance variables to match what is in response
def set_self_from_response(response)
self.category = response[:category]
self.ciid = response[:ciid]
#self.cust_date1 = response[:cust_date1]
#self.cust_date2 = response[:cust_date2]
self.cust_int1 = response[:cust_int1]
self.cust_int2 = response[:cust_int2]
self.cust_list1 = response[:cust_list1]
self.cust_list2 = response[:cust_list2]
self.cust_notes = response[:cust_notes]
self.cust_text1 = response[:cust_text1]
self.cust_text2 = response[:cust_text2]
self.description = response[:description]
self.end_time = response[:end_time]
self.estimation = response[:estimation]
self.id = response[:id]
self.notes = response[:notes]
self.progress = response[:progress]
self.project_id = response[:project_id]
self.start_time = response[:start_time]
self.status = response[:status]
self.task_dependency = response[:task_dependency]
self.task_dependency_type = response[:task_dependency_type]
self.title = response[:title]
self.version = response[:version]
end
end
|
MattMencel/ruby-sysaid
|
lib/sysaid.rb
|
<gh_stars>0
require 'savon'
# Custom error class used for throwing exceptions to this gem's user
class SysAidException < StandardError
end
# The main SysAid class
class SysAid
@@logged_in = false
@@server_settings = { account: nil, username: nil, password: <PASSWORD>, wsdl_uri: nil, debug: false }
# Accessor for internal SysaidApiService object.
# Used by SysAid::Ticket
def self.client
@@client
end
# Proxy for @@client.call but allows us to catch the various exceptions which may happen
# due to network errors, SOAP errors, etc., which otherwise would have to be caught in
# many different places.
def self.call(method, message)
begin
return @@client.call(method, message)
rescue SocketError => e
raise SysAidException, "Unable to fetch user information from SysAid server: #{e.message}"
rescue Errno::EHOSTUNREACH => e
raise SysAidException, "Unable to save user due to server being unreachable: #{e.message}"
rescue Savon::SOAPFault => e
raise SysAidException, "Unable to save user due to SOAP communications error: #{e.message}"
end
end
# Accessor for session ID returned by SysAid server.
# Used by SysAid::Ticket
def self.session_id
@@session_id
end
# Accessor for server settings.
# Used by SysAid::Ticket
def self.server_settings
@@server_settings
end
def self.server_settings=(server_settings)
@@server_settings = server_settings
# If they don't pass in debug, set it to false to maintain default settings
@@server_settings[:debug] = false if server_settings[:debug].nil?
end
# The SysAid API isn't clear on what creates an API timeout. It's possible to login
# and make SOAP calls many minutes later but the API _seems_ to timeout at some point.
# With the exception of the added delay, there's no harm in simply logging in over and
# over with each call, so we do this in ensure_logged_in until we can get a better answer
# on what we can do with the SysAid API to _actually_ ensure we're logged in.
def self.ensure_logged_in
self.login unless self.logged_in?
end
# Returns true if logged into SysAid server
# Note: By design, logged_in? will try to log in if it isn't already
#
# Example:
# >> SysAid.logged_in?
# => true
def self.logged_in?
puts "SysAid.logged_in? called" if @@server_settings[:debug]
# Until official word comes from the company, we're going to login every time
# to avoid a problem with undetected timeouts.
#if @@logged_in == false
login
#end
if @@logged_in
return true
else
return false
end
end
# self.login does not require credentials be passed every time.
# SysAid sometimes times out the session and we can simply call 'login' again with the
# saved credentials to get around the timeout.
def self.login(account = nil, username = nil, password = <PASSWORD>, wsdl_uri = nil, debug = nil)
puts "SysAid.login" if @@server_settings[:debug]
if account and username and password and wsdl_uri
# Save server settings in case we need to log in again later
@@server_settings = { :account => account, :username => username, :password => password, :wsdl_uri => wsdl_uri }
# 'debug' parameter cannot default to false else it would override default, so use nil and check
@@server_settings[:debug] = debug if debug != nil
end
begin
@@client = Savon.client(wsdl: @@server_settings[:wsdl_uri], log: @@server_settings[:debug])
# login
unless @@server_settings[:account].nil?
# Call login
response = self.call(:login, message: { accountId: @@server_settings[:account], userName: @@server_settings[:username], password: @@server_settings[:password] })
# Retrieve response
@@session_id = response.to_hash[:login_response][:return]
@@logged_in = true
end
rescue Net::ReadTimeout => e
# This isn't the API timeout, this is a normal socket timeout error.
raise SysAidException, "Unable to log into SysAid server: #{e.message}"
end
end
end
require 'sysaid/activity'
require 'sysaid/project'
require 'sysaid/task'
require 'sysaid/ticket'
require 'sysaid/user'
|
MattMencel/ruby-sysaid
|
lib/sysaid/activity.rb
|
require 'date'
class SysAid::Activity
attr_accessor :ciid, :cust_int1, :cust_int2, :cust_int3, :cust_int4, :cust_list1, :cust_list2, :description, :from_time, :id, :sr_id, :to_time, :user
def initialize
reset_all_attributes
end
# Needed by both initialize and delete (to empty out the object when deleted)
def reset_all_attributes
self.ciid = nil
self.cust_int1 = nil
self.cust_int2 = nil
self.cust_int3 = nil
self.cust_int4 = nil
self.cust_list1 = nil
self.cust_list2 = nil
self.description = nil
self.from_time = Date.new
self.id = nil
self.sr_id = nil
self.to_time = Date.new
self.user = nil
end
# Returns an array of Activity IDs based on ticket_id.
# Returns false on error.
def self.find_by_ticket_id(ticket_id)
SysAid.ensure_logged_in
response = SysAid.call(:execute_select_query, message: sql_query(" service_req_id = #{ticket_id}"))
if response.to_hash[:execute_select_query_response][:return]
return response.to_hash[:execute_select_query_response][:return]
end
return false
end
# Returns a specific Activity based on an Activity ID
def self.find_by_id(activity_id)
activity = SysAid::Activity.new
activity.id = activity_id
return nil unless activity.refresh
return activity
end
# Loads the latest ticket information from the SysAid server
def refresh
SysAid.ensure_logged_in
response = SysAid.call(:load_by_string_id, message: to_xml)
if response.to_hash[:load_by_string_id_response][:return]
set_self_from_response(response.to_hash[:load_by_string_id_response][:return])
return true
end
return false
end
# Saves an activity back to the SysAid server
#
# Example:
# >> activity_object.save
# => true
def save
SysAid.ensure_logged_in
# Save it via the SOAP API
response = SysAid.call(:save, message: to_xml(false))
if response.to_hash[:save_response][:return]
# In the case of new activities, the SysAid response will be the assigned ID
self.id = response.to_hash[:save_response][:return] unless self.id
return true
else
return false
end
end
# Deletes an activity from the SysAid server
#
# No return value as SysAid's 'delete' call returns void. No idea why.
#
# Example:
# >> activity_object.delete
# => true
def delete
SysAid.ensure_logged_in
SysAid.call(:delete, message: to_xml(false))
reset_all_attributes
end
private
def self.sql_query(query)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiServiceRequestActivity")
xml = builder.condition(query)
xml
end
def to_xml(include_id = true)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiServiceRequestActivity") { |b|
b.CIId(self.ciid, 'xsi:type' => 'xsd:int')
b.custInt1(self.cust_int1, 'xsi:type' => 'xsd:int')
b.custInt2(self.cust_int2, 'xsi:type' => 'xsd:int')
b.custInt3(self.cust_int3, 'xsi:type' => 'xsd:int')
b.custInt4(self.cust_int4, 'xsi:type' => 'xsd:int')
b.custList1(self.cust_list1, 'xsi:type' => 'xsd:int')
b.custList2(self.cust_list2, 'xsi:type' => 'xsd:int')
b.description(self.description, 'xsi:type' => 'xsd:string')
b.fromTime(self.from_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.id(self.id, 'xsi:type' => 'xsd:int')
b.srID(self.sr_id, 'xsi:type' => 'xsd:int')
b.toTime(self.to_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.user(self.user, 'xsi:type' => 'xsd:string')
}
xml = builder.id(self.id) if include_id
xml
end
# Update instance variables to match what is in response
def set_self_from_response(response)
self.ciid = response[:ci_id]
self.cust_int1 = response[:cust_int1]
self.cust_int2 = response[:cust_int2]
self.cust_int3 = response[:cust_int3]
self.cust_int4 = response[:cust_int4]
self.cust_list1 = response[:cust_list1]
self.cust_list2 = response[:cust_list2]
self.description = response[:description]
self.from_time = response[:from_time]
self.id = response[:id]
self.sr_id = response[:sr_id]
self.to_time = response[:to_time]
self.user = response[:user]
end
end
|
MattMencel/ruby-sysaid
|
lib/sysaid/project.rb
|
require 'date'
class SysAid::Project
attr_accessor :assigned_group, :category, :company, :cust_date1, :cust_date2, :cust_int1, :cust_int2, :cust_list1,
:cust_list2, :cust_notes, :custom_date_fields, :custom_fields, :cust_text1, :cust_text2, :description,
:end_time, :id, :incident_title, :manager, :notes, :progress, :raw_estimation, :request_group,
:start_time, :status, :title, :version
def initialize
self.start_time = Date.new
self.end_time = Date.new
end
def self.find_by_id(project_id)
project = SysAid::Project.new
project.id = project_id
return nil unless project.refresh
return project
end
def self.find_by_query(query)
SysAid.ensure_logged_in
response = SysAid.call(:execute_select_query, message: sql_query(query))
if response.to_hash[:execute_select_query_response][:return]
return response.to_hash[:execute_select_query_response][:return]
end
return false
end
# Loads the latest project information from the SysAid server
def refresh
SysAid.ensure_logged_in
response = SysAid.call(:load_by_string_id, message: to_xml)
if response.to_hash[:load_by_string_id_response][:return]
set_self_from_response(response.to_hash[:load_by_string_id_response][:return])
return true
end
return false
end
# Saves a project back to the SysAid server
#
# Example:
# >> project_object.save
# => true
def save
SysAid.ensure_logged_in
# Save it via the SOAP API
response = SysAid.call(:save, message: to_xml(false))
if response.to_hash[:save_response][:return]
return true
else
return false
end
end
# Deletes a project from the SysAid server
#
# No return value as SysAid's 'delete' call returns void. No idea why.
#
# Example:
# >> project_object.delete
# => true
def delete
SysAid.ensure_logged_in
SysAid.call(:delete, message: to_xml(false))
end
private
def self.sql_query(query)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiProject")
xml = builder.condition(query)
xml
end
def to_xml(include_id = true)
builder = Builder::XmlMarkup.new
builder.sessionId(SysAid.session_id)
xml = builder.apiSysObj('xsi:type' => "tns:apiProject") { |b|
b.assignedGroup(self.assigned_group, 'xsi:type' => 'xsd:string')
b.category(self.category, 'xsi:type' => 'xsd:int')
b.company(self.company, 'xsi:type' => 'xsd:int')
b.custInt1(self.cust_int1, 'xsi:type' => 'xsd:int')
b.custInt2(self.cust_int2, 'xsi:type' => 'xsd:int')
b.custList1(self.cust_list1, 'xsi:type' => 'xsd:int')
b.custList2(self.cust_list2, 'xsi:type' => 'xsd:int')
b.custNotes(self.cust_notes, 'xsi:type' => 'xsd:string')
b.custText1(self.cust_text1, 'xsi:type' => 'xsd:string')
b.custText2(self.cust_text2, 'xsi:type' => 'xsd:string')
b.customDateFields
b.description(self.description, 'xsi:type' => 'xsd:string')
b.endTime(self.end_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.id(self.id, 'xsi:type' => 'xsd:int')
b.incidentTitle(self.incident_title, 'xsi:type' => 'xsd:string')
b.manager(self.manager, 'xsi:type' => 'xsd:string')
b.notes(self.notes, 'xsi:type' => 'xsd:string')
b.progress(self.progress, 'xsi:type' => 'xsd:int')
b.rawEstimation(self.raw_estimation, 'xsi:type' => 'xsd:int')
b.requestGroup(self.request_group, 'xsi:type' => 'xsd:string')
b.startTime(self.start_time.rfc3339, 'xsi:type' => 'xsd:dateTime')
b.status(self.status, 'xsi:type' => 'xsd:int')
b.title(self.title, 'xsi:type' => 'xsd:string')
b.version(self.version, 'xsi:type' => 'xsd:int')
}
xml = builder.id(self.id) if include_id
xml
end
# Update instance variables to match what is in response
def set_self_from_response(response)
self.assigned_group = response[:assign_group]
self.category = response[:category]
self.company = response[:company]
self.cust_int1 = response[:cust_int1]
self.cust_int2 = response[:cust_int2]
self.cust_list1 = response[:cust_list1]
self.cust_list2 = response[:cust_list2]
self.cust_notes = response[:cust_notes]
self.cust_text1 = response[:cust_text1]
self.cust_text2 = response[:cust_text2]
self.description = response[:description]
self.end_time = response[:end_time]
self.id = response[:id]
self.incident_title = response[:incident_title]
self.manager = response[:manager]
self.notes = response[:notes]
self.progress = response[:progress]
self.raw_estimation = response[:raw_estimation]
self.request_group = response[:request_group]
self.start_time = response[:start_time]
self.status = response[:status]
self.title = response[:title]
self.version = response[:version]
end
end
|
defus/ansible-monit
|
test/integration/default/serverspec/monit_spec.rb
|
<reponame>defus/ansible-monit<filename>test/integration/default/serverspec/monit_spec.rb
require 'spec_helper'
describe 'Monit' do
describe service('monit') do
it { should be_enabled }
it { should be_running }
end
# describe port(2812) do
# it { should be_listening.on('0.0.0.0').with('tcp') }
# end
describe file('/etc/monitrc') do
it { should be_file }
it { should be_owned_by 'monit' }
its(:content) { should match /443/ }
end
describe file('/opt/monit/.monit.pid') do
it { should be_file }
it { should be_owned_by 'monit' }
its(:size) { should > 0 }
end
describe file('/var/log/monit/monit.log') do
it { should be_file }
it { should be_owned_by 'monit' }
its(:size) { should > 0 }
end
end
|
matthewrudy/workling
|
lib/workling/rudeq.rb
|
<reponame>matthewrudy/workling
module Workling
module Rudeq
def self.config
@@config ||= {:queue_class => "RudeQueue"}
end
end
end
|
matthewrudy/workling
|
test/rudeq_client_test.rb
|
<gh_stars>1-10
require File.dirname(__FILE__) + '/test_helper'
context "The Rudeq client" do
specify "should by default set a RudeQueue as its :queue" do
client = Workling::Rudeq::Client.new
client.queue.should == RudeQueue
end
specify "should user Rudeq.config[:queue_class] as the class" do
before = Workling::Rudeq.config[:queue_class]
Workling::Rudeq.config[:queue_class] = "String"
client = Workling::Rudeq::Client.new
client.queue.should == String
Workling::Rudeq.config[:queue_class] = before
end
specify "should defer :get to the RudeQueue" do
RudeQueue.expects(:get).with(:abc)
client = Workling::Rudeq::Client.new
client.get(:abc)
end
specify "should defer :set to the RudeQueue" do
RudeQueue.expects(:set).with(:abc, "some value")
client = Workling::Rudeq::Client.new
client.set(:abc, "some value")
end
end
|
matthewrudy/workling
|
lib/workling/rudeq/client.rb
|
<filename>lib/workling/rudeq/client.rb
require 'workling/rudeq'
module Workling
module Rudeq
class Client
attr_reader :queue
def initialize
@queue = Workling::Rudeq.config[:queue_class].constantize
end
def method_missing(method, *args)
@queue.send(method, *args)
end
end
end
end
|
matthewrudy/workling
|
test/test_helper.rb
|
<gh_stars>1-10
plugin_test = File.dirname(__FILE__)
plugin_root = File.join plugin_test, '..'
plugin_lib = File.join plugin_root, 'lib'
require 'rubygems'
require 'active_support'
require 'test/spec'
require 'mocha'
gem 'memcache-client'
require 'memcache'
$:.unshift plugin_lib, plugin_test
require "mocks/spawn"
require "mocks/logger"
require "mocks/rude_queue"
require "workling"
require "workling/discovery"
require "workling/starling/routing/class_and_method_routing"
require "workling/starling/poller"
require "workling/rudeq/poller"
require "workling/remote"
require "workling/remote/runners/not_remote_runner"
require "workling/remote/runners/spawn_runner"
require "workling/remote/runners/rudeq_runner"
require "workling/remote/runners/starling_runner"
require "workling/return/store/memory_return_store"
require "workling/return/store/starling_return_store"
require "workling/return/store/rudeq_return_store"
RAILS_ROOT = File.dirname(__FILE__) + "/.." # fake the rails root directory.
RAILS_ENV = "test"
RAILS_DEFAULT_LOGGER = Logger.new
# worklings are in here.
Workling.load_path ="#{ plugin_root }/test/workers"
Workling::Return::Store.instance = Workling::Return::Store::MemoryReturnStore.new
Workling::Discovery.discover!
|
matthewrudy/workling
|
lib/workling/remote/runners/rudeq_runner.rb
|
<reponame>matthewrudy/workling
require 'workling/remote/runners/base'
module Workling
module Remote
module Runners
class RudeqRunner < Workling::Remote::Runners::Base
cattr_accessor :routing
cattr_accessor :client
def initialize
RudeqRunner.client = Workling::Rudeq::Client.new
RudeqRunner.routing = Workling::Starling::Routing::ClassAndMethodRouting.new
end
def run(clazz, method, options = {})
RudeqRunner.client.set(@@routing.queue_for(clazz, method), options)
return nil # empty.
end
end
end
end
end
|
matthewrudy/workling
|
lib/workling/return/store/rudeq_return_store.rb
|
<gh_stars>1-10
require 'workling/return/store/base'
require 'workling/rudeq/client'
module Workling
module Return
module Store
class RudeqReturnStore < Base
cattr_accessor :client
def initialize
self.class.client = Workling::Rudeq::Client.new
end
def set(key, value)
self.class.client.set(key, value)
end
def get(key)
self.class.client.get(key)
end
end
end
end
end
|
matthewrudy/workling
|
test/rudeq_runner_test.rb
|
require File.dirname(__FILE__) + '/test_helper.rb'
context "the RudeQ runner" do
setup do
@before = Workling::Remote.dispatcher
end
specify "should set up a RudeQ client" do
Workling::Remote.dispatcher = Workling::Remote::Runners::RudeqRunner.new
Workling::Remote.dispatcher.client.should.not.equal nil
Workling::Remote.dispatcher.client.queue.should.equal RudeQueue
end
specify ":run should use Starling routing" do
RudeQueue.expects(:set).with("utils__echo", "hello")
Workling::Remote::Runners::RudeqRunner.new.run(Util, :echo, "hello")
end
teardown do
Workling::Remote.dispatcher = @before
end
end
|
matthewrudy/workling
|
lib/workling/rudeq/poller.rb
|
require 'workling/rudeq'
module Workling
module Rudeq
class Poller
cattr_accessor :sleep_time # Seconds to sleep before looping
cattr_accessor :reset_time # Seconds to wait while resetting connection
def initialize(routing)
Poller.sleep_time = Workling::Rudeq.config[:sleep_time] || 2
Poller.reset_time = Workling::Rudeq.config[:reset_time] || 30
@routing = routing
@workers = ThreadGroup.new
end
def logger
Workling::Base.logger
end
def listen
# Allow concurrency for our tasks
ActiveRecord::Base.allow_concurrency = true
# Create a thread for each worker.
Workling::Discovery.discovered.each do |clazz|
logger.debug("Discovered listener #{clazz}")
@workers.add(Thread.new(clazz) { |c| clazz_listen(c) })
end
# Wait for all workers to complete
@workers.list.each { |t| t.join }
# Clean up all the connections.
ActiveRecord::Base.verify_active_connections!
end
# gracefully stop processing
def stop
@workers.list.each { |w| w[:shutdown] = true }
end
##
## Thread procs
##
# Listen for one worker class
def clazz_listen(clazz)
logger.debug("Listener thread #{clazz.name} started")
# Read thread configuration if available
if Rudeq.config.has_key?(:listeners)
if Rudeq.config[:listeners].has_key?(clazz.to_s)
config = Rudeq.config[:listeners][clazz.to_s].symbolize_keys
thread_sleep_time = config[:sleep_time] if config.has_key?(:sleep_time)
end
end
hread_sleep_time ||= self.class.sleep_time
connection = Workling::Rudeq::Client.new
puts "** Starting Workling::Rudeq::Client for #{clazz.name} queue"
# Start dispatching those messages
while (!Thread.current[:shutdown]) do
begin
# Keep MySQL connection alive
unless ActiveRecord::Base.connection.active?
unless ActiveRecord::Base.connection.reconnect!
logger.fatal("FAILED - Database not available")
break
end
end
# Dispatch and process the messages
n = dispatch!(connection, clazz)
logger.debug("Listener thread #{clazz.name} processed #{n.to_s} queue items") if n > 0
sleep(self.class.sleep_time) unless n > 0
end
end
logger.debug("Listener thread #{clazz.name} ended")
end
# Dispatcher for one worker class.
# Returns the number of worker methods called
def dispatch!(connection, clazz)
n = 0
for queue in @routing.queue_names_routing_class(clazz)
begin
result = connection.get(queue)
if result
n += 1
handler = @routing[queue]
method_name = @routing.method_name(queue)
logger.debug("Calling #{handler.class.to_s}\##{method_name}(#{result.inspect})")
handler.send(method_name, result)
end
rescue
logger.error("FAILED to connect with queue #{ queue }: #{ e } }")
raise e
rescue Object => e
logger.error("FAILED to process queue #{ queue }. #{ @routing[queue] } could not handle invocation of #{ @routing.method_name(queue) } with #{ result.inspect }: #{ e }.\n#{ e.backtrace.join("\n") }")
end
end
return n
end
end
end
end
|
matthewrudy/workling
|
test/rudeq_return_store_test.rb
|
require File.dirname(__FILE__) + '/test_helper'
context "the RudeQ return store" do
def get_store
Workling::Return::Store::RudeqReturnStore.new
end
specify "should defer :get to the RudeQueue" do
RudeQueue.expects(:get).with(:abc)
store = get_store
store.get(:abc)
end
specify "should defer :set to the RudeQueue" do
RudeQueue.expects(:set).with(:abc, "some value")
store = get_store
store.set(:abc, "some value")
end
end
|
matthewrudy/workling
|
test/rudeq_poller_test.rb
|
<reponame>matthewrudy/workling
require File.dirname(__FILE__) + '/test_helper.rb'
context "the RudeQ poller" do
setup do
routing = Workling::Starling::Routing::ClassAndMethodRouting.new
@client = Workling::Rudeq::Poller.new(routing)
end
specify "should invoke Util.echo with the arg 'hello' if the string 'hello' is set onto the queue utils__echo" do
Util.any_instance.expects(:echo).with("hello")
RudeQueue.set("utils__echo", "hello")
@client.dispatch!(RudeQueue, Util)
end
end
|
incominghq/incoming-ruby
|
spec/incoming_spec.rb
|
<reponame>incominghq/incoming-ruby<filename>spec/incoming_spec.rb
require 'spec_helper'
describe Incoming do
it 'has a version number' do
expect(Incoming::VERSION).not_to be nil
end
end
|
incominghq/incoming-ruby
|
lib/incoming/instruction_set_converter.rb
|
require 'json'
module Incoming
class InstructionSetLoader
def initialize
@tasks = []
end
def method_missing(name, args)
raise InvalidArgumentError, "Arguments should be named" unless args.kind_of?(Hash)
task = {name: name, options: args}
if block_given?
l = InstructionSetLoader.new
l.instance_exec(&Proc.new)
task[:tasks] = l.to_arr
end
@tasks << task
end
def to_arr
@tasks.dup
end
end
class InstructionSetConverter
def self.to_arr(fn)
l = InstructionSetLoader.new
l.instance_eval(File.read(fn), fn)
l.to_arr
end
def self.to_json(fn)
JSON.pretty_generate(to_arr(fn))
end
end
end
|
incominghq/incoming-ruby
|
lib/incoming.rb
|
<reponame>incominghq/incoming-ruby
require "incoming/version"
require 'apiture'
module Incoming
Client = Apiture.load_api(File.join(File.dirname(__FILE__), 'incominghq.yml'))
end
|
incominghq/incoming-ruby
|
spec/instruction_set_converter_spec.rb
|
<filename>spec/instruction_set_converter_spec.rb<gh_stars>0
require 'spec_helper'
require 'incoming/instruction_set_converter'
describe Incoming::InstructionSetConverter do
subject { described_class }
def ins_file(name)
File.join(File.dirname(__FILE__), 'fixtures', 'files', 'instruction_set', "#{name}.ins")
end
def ins_to_arr(name)
subject.to_arr(ins_file(name))
end
it "should convert a simple instruction" do
ins = ins_to_arr :simple
expect(ins.first[:name]).to eq :set
options = ins.first[:options]
expect(options).to_not be_nil
expect(options[:key]).to eq "foo"
expect(options[:value]).to eq "bar"
end
it "should convert to json" do
json = subject.to_json(ins_file(:simple))
expect(json).to eq <<JSON.chomp
[
{
"name": "set",
"options": {
"key": "foo",
"value": "bar"
}
}
]
JSON
end
end
|
sevenc-nanashi/brainfuck-extended
|
brainfuck-extended.gemspec
|
Gem::Specification.new do |s|
s.name = "brainfuck-extended"
s.version = "1.0.1"
s.summary = "An extended BrainFuck."
s.description = <<-EOF
An extended BrainFuck.
You can use random, you can use 2D data, you can use temp data.
EOF
s.authors = ["sevenc-nanashi"]
s.email = "<EMAIL>"
s.files = Dir["main.rb", "bin/*"]
s.homepage =
"https://github.com/sevenc-nanashi/brainfuck-extended"
s.license = "MIT"
s.metadata = {
"bug_tracker_uri" => "https://github.com/sevenc-nanashi/brainfuck-extended/issues",
"homepage_uri" => "https://github.com/sevenc-nanashi/brainfuck-extended",
"source_code_uri" => "https://github.com/sevenc-nanashi/brainfuck-extended",
}
s.add_runtime_dependency "colorize"
s.add_runtime_dependency "tty-cursor"
s.bindir = "bin"
s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) }
end
|
sevenc-nanashi/brainfuck-extended
|
main.rb
|
<filename>main.rb
require "io/console"
require 'io/console/size'
require "colorize"
require "tty-cursor"
require 'optparse'
opt = OptionParser.new
visible = false
debug = false
opt.on('-v', "--verbose", "Run with verbose mode") { |v|
visible = v
}
opt.on('-d', "--debug", "Run with debug mode") {|v|
debug = v
if v
visible = true
end
}
opt.banner += ' file'
opt.parse!(ARGV)
script = ""
if ARGV[0] == nil
script = "
///++++++++[^^^++++++++///-]^^^:/
;///++++++++[^^^++++///-]
/++++[^^^++++++++///-]^^^^^
>;++++++.
</:>;+++++++++.
+++.
;+++++.
</.
^^:>;///++[^^^+++++++///-]^^^.
/<:>;///+++[^^^+++++///-]^^^.
:>;<+++++.
</.
^^>+++++.
/----.
<:>>;+++++.
:>;--.
++++++.
<+.
>.
<-.
-.
<</:>;///+++[^^^++++///-]^^^++.
"
elsif not File.exists?(ARGV[0])
script = "
///++++++++[^^^++++++++///-]^^^:/
;///++++++++[^^^++++///-]
/++++[^^^++++++++///-]^^^^^
>;++++++.
:>;<</:>;+++++++++.
+++.
;+++++.
</.
^^:>;///++[^^^+++++++///-]^^^.
/<:>;///+++[^^^+++++///-]^^^.
:>;<+++++.
</.
^^>>.
/.
:>;++++++.
<-.
<<:>;++++.
</:>;///+++[^^^++++///-]^^^++.
"
else
File.open(ARGV[0], "r") do |f|
script = f.read
end
end
cursor = TTY::Cursor
index = 0
cursor_x = 0
cursor_y = 0
field = [[0]]
brackets = []
bracket_pairs = {}
clipboard = 0
output = ""
WIDTH = IO::console_size[1]
script = script.split("").filter{ |c| ".,/^<>[]?+-:;".include?(c)}.join("")
$finish_flag = false
if visible
print cursor.clear_screen
puts (" " * WIDTH).on_blue
print " ".on_blue
print "Brainfuck Extended".center(WIDTH - 4)
puts " ".on_blue
puts (" " * WIDTH).on_blue
puts ""
end
# Lint
lint_brackets = []
script.split("").each_with_index do |c, i|
case c
when "["
lint_brackets << i
when "]"
n = lint_brackets.delete_at(-1)
if n == nil
raise "SyntaxError: Unmatched brackets"
else
bracket_pairs[n] = i
end
end
end
# Execute
until index >= script.length
current_chr = script[index]
case current_chr
when "+"
field[cursor_y][cursor_x] += 1
when "-"
field[cursor_y][cursor_x] -= 1
when ">"
cursor_x += 1
if field[cursor_y].length <= cursor_x
field.each do |f|
f << 0
end
end
when "<"
cursor_x -= 1
when "."
if visible
output += field[cursor_y][cursor_x].chr
else
$stdout.print field[cursor_y][cursor_x].chr
end
when ","
field[cursor_y][cursor_x] = $stdin.getch.ord
when "["
if field[cursor_y][cursor_x] != 0
brackets << index
else
until script[index] == "]"
index += 1
end
end
when "]"
if field[cursor_y][cursor_x] == 0
brackets.delete_at(0)
else
index = brackets[-1]
end
when "?"
field[cursor_y][cursor_x] = rand(0..255)
when ":"
clipboard = field[cursor_y][cursor_x]
when ";"
field[cursor_y][cursor_x] = clipboard
when "/"
cursor_y += 1
if field.length <= cursor_y
field << Array.new(field[0].length) { 0 }
end
when "^"
cursor_y -= 1
end
if cursor_x < 0
raise "Out of X range: #{cursor_x}"
end
if cursor_y < 0
raise "Out of Y range: #{cursor_y}"
end
unless (0..255).include? field[cursor_y][cursor_x]
raise "Overflow: #{cursor_x}, #{cursor_y}"
end
if visible
sleep(debug ? 0.1 : 0.01)
print cursor.move_to 0, 4
print " ".on_light_blue
print " Source "
puts (" " * (WIDTH - 8 - 2)).on_light_blue
print cursor.clear_line
running_bracket_ends = []
primary_bracket_end = -1
script.split("").each_with_index do |c, i|
if script.length <= WIDTH
do_print = true
elsif index < WIDTH / 2
do_print = i < WIDTH
elsif index >= script.length - WIDTH / 2
do_print = i > script.length - WIDTH
else
do_print = [(index - i).abs, 0].max < WIDTH / 2
end
if brackets[-1] == i
primary_bracket_end = bracket_pairs[i]
print c.light_green if do_print
elsif primary_bracket_end == i
print c.light_green if do_print
elsif brackets.include?(i)
running_bracket_ends << bracket_pairs[i]
print c.green if do_print
elsif index == i
print c.yellow if do_print
elsif running_bracket_ends.include?(i)
print c.green if do_print
else
print c if do_print
end
end
puts
print " ".on_light_blue
print " Output "
puts (" " * (WIDTH - 8 - 2)).on_light_blue
puts output
pos_txt = "#{clipboard} #{cursor_x}, #{cursor_y}"
print " ".on_light_blue
print " Field "
print (" " * (WIDTH - 7 - 2 - pos_txt.length - 2)).on_light_blue
print pos_txt.on_light_blue.light_white
puts " ".on_light_blue
max_length = field.flatten.map { |i| i.to_s.length }.max
print cursor.clear_line
print " "
field[0].length.times do |i|
print i.to_s.rjust(max_length).colorize(i == cursor_x ? :light_blue : :blue)
print " "
end
print "\n"
field.each_with_index do |f, j|
print cursor.clear_line
print j.to_s.colorize(j == cursor_y ? :light_blue : :blue)
print " "
f.each_with_index do |v, i|
res = v.to_s.rjust(max_length)
case [i,j]
in [^cursor_x, ^cursor_y]
print res.light_green
in [^cursor_x, _] | [_, ^cursor_y]
print res.green
else
print res
end
print " "
end
print "\n"
end
end
index += 1
end
if visible
print "Waiting for input..."
$stdin.getch
end
|
bmarsha72/musical-api
|
controllers/account_controller.rb
|
class AccountController < ApplicationController
@username = ""
get '/' do
#login /registration page
erb :login
end
post '/register' do
#accept the params from a post to create a user (bcrypt)
@username = params[:username]
@password = params[:password]
@email = params[:email]
if does_user_exist?(@username) == true
@account_message = "User Already Exists"
return erb :login_notice
end
password_salt = BCrypt::Engine.generate_salt
password_hash = BCrypt::Engine.hash_secret(@password, password_salt)
#binding.pry
@model = Account.new
@model.username = @username
@model.email = @email
@model.password_hash = password_hash
@model.password_salt = password_salt
@model.save
@account_message = "You have successfully registered and logged in"
######################## why the fuck does this work?!?!?
session[:user] = @model
@username = session[:user][:username]
erb :login_notice
########################
end
post '/login' do
# params { :username, :password, :email }
@username = params[:username]
@password = <PASSWORD>[:password]
#accept params from a post to check if a user exists
#and if so, log them in
if does_user_exist?(@username) == false
@account_message = "User Already Exists"
return erb :login_notice
end
@model = Account.where(:username => @username).first!
if @model.password_hash == <PASSWORD>::Engine.hash_secret(@password, @model.password_salt)
@account_message = "Welcome Back"
#########################
session[:user] = @model
@username = session[:user][:username]
return erb :login_notice
#########################
else
@account_message = "Password did not match, try again"
return erb :login_notice
end
end
get '/logout' do
#user leaves - set session to nil. they will need to log in again
session[:user] = nil
@username = nil
redirect '/'
end
post '/song' do
session[:user] = @username
@model = Song.new
@model.name = params[:name]
@model.duration = params[:duration]
@model.artist = params[:artist]
@model.save
@account_message = "Thanks for entering a song"
return erb :song
end
get '/song' do
session[:user] = @username
@account_message = "enter a song"
return erb :song
end
get '/supersecret' do
# test of user authentication
# hide some hash/json and only show to logged in users
if is_not_authenticated == false
erb :secret_club
else
@account_message = "You shall not pass!"
erb :login_notice
end
end
end
|
bmarsha72/musical-api
|
config.ru
|
require 'sinatra/base'
#controllers
require './controllers/application_controller'
require './controllers/account_controller'
require './controllers/artist_controller'
require './controllers/song_controller'
#models
require './models/artist'
require './models/song'
require './models/account'
#map controllers to routes
map('/') { run ApplicationController }
map('/account') { run AccountController }
map('/artist') { run ArtistController }
|
bmarsha72/musical-api
|
models/account.rb
|
class Account < ActiveRecord::Base
end
|
bmarsha72/musical-api
|
db/migrate/20170119202252_songs.rb
|
<gh_stars>0
class Songs < ActiveRecord::Migration[5.0]
def change
create_table :songs do |tbl|
tbl.string :name
tbl.string :artist
tbl.string :duration
end
end
end
|
bmarsha72/musical-api
|
controllers/song_controller.rb
|
<reponame>bmarsha72/musical-api<filename>controllers/song_controller.rb
class SongController < ApplicationController
end
|
bmarsha72/musical-api
|
controllers/application_controller.rb
|
class ApplicationController < Sinatra::Base
@account_message = ""
@username = ""
require 'bundler'
Bundler.require
ActiveRecord::Base.establish_connection(
:adapter => 'mysql2',
:database => 'musical_api2'
)
set :public_folder, File.expand_path('../../public', __FILE__)
set :views, File.expand_path('../../views', __FILE__)
enable :sessions
not_found do
erb :not_found #404 page
end
def does_user_exist?(username)
user = Account.find_by(:username => username.to_s)
if user
return true
else
return false
end
end
def is_not_authenticated
session[:user].nil? #boolean
end
get '/' do
erb :home
end
end
|
bmarsha72/musical-api
|
controllers/artist_controller.rb
|
<reponame>bmarsha72/musical-api
class ArtistController < ApplicationController
end
|
fjuan/padel
|
test/unit/helpers/my_account_helper_test.rb
|
<filename>test/unit/helpers/my_account_helper_test.rb
require 'test_helper'
class MyAccountHelperTest < ActionView::TestCase
end
|
fjuan/padel
|
app/controllers/application_controller.rb
|
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_user!
before_filter :set_locale
private
def set_locale
I18n.locale = :es
end
end
|
fjuan/padel
|
app/controllers/calendars_controller.rb
|
class CalendarsController < ApplicationController
def show
@users_by_availability = User.by_availability
@weekdays = %w(monday tuesday wednesday thursday friday saturday sunday)
@date = params[:date] && Date.parse(params[:date]) || Date.today
@beginning_of_week = @date.beginning_of_week
@end_of_week = @date.end_of_week
@weekdays = (@beginning_of_week..@end_of_week)
end
end
|
fjuan/padel
|
app/models/user.rb
|
<filename>app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_presence_of :name, :phone
# Setup accessible (or protected) attributes for your model
attr_accessible :name, :phone, :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
weekdays = %w(monday tuesday wednesday thursday friday saturday sunday)
(10..22).each do |hour|
weekdays.each do |day|
attr_accessible "#{day}_#{hour}"
end
end
def self.by_availability
@by_availability ||= {}
weekdays = %w(monday tuesday wednesday thursday friday saturday sunday)
(10..22).each do |hour|
weekdays.each do |day|
@by_availability["#{day}_#{hour}"] = self.where("#{day}_#{hour}" => true)
end
end
return @by_availability
end
def has_name_and_phone?
name.present? && phone.present?
end
end
|
fjuan/padel
|
app/controllers/my_accounts_controller.rb
|
<reponame>fjuan/padel
class MyAccountsController < ApplicationController
def show
@user = current_user
@weekdays = %w(monday tuesday wednesday thursday friday saturday sunday)
unless @user.has_name_and_phone?
flash[:notice] = 'Please add your name and phone number'
end
end
end
|
fjuan/padel
|
db/migrate/20130605185715_add_availability_fields_to_user.rb
|
class AddAvailabilityFieldsToUser < ActiveRecord::Migration
def change
weekdays = %w(monday tuesday wednesday thursday friday saturday sunday)
(10..22).each do |hour|
weekdays.each do |day|
add_column :users, "#{day}_#{hour}", :boolean, default: false
end
end
end
end
|
fjuan/padel
|
db/schema.rb
|
<reponame>fjuan/padel
# 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 to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20130605185715) do
create_table "users", :force => true do |t|
t.string "name"
t.string "phone"
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.boolean "monday_10", :default => false
t.boolean "tuesday_10", :default => false
t.boolean "wednesday_10", :default => false
t.boolean "thursday_10", :default => false
t.boolean "friday_10", :default => false
t.boolean "saturday_10", :default => false
t.boolean "sunday_10", :default => false
t.boolean "monday_11", :default => false
t.boolean "tuesday_11", :default => false
t.boolean "wednesday_11", :default => false
t.boolean "thursday_11", :default => false
t.boolean "friday_11", :default => false
t.boolean "saturday_11", :default => false
t.boolean "sunday_11", :default => false
t.boolean "monday_12", :default => false
t.boolean "tuesday_12", :default => false
t.boolean "wednesday_12", :default => false
t.boolean "thursday_12", :default => false
t.boolean "friday_12", :default => false
t.boolean "saturday_12", :default => false
t.boolean "sunday_12", :default => false
t.boolean "monday_13", :default => false
t.boolean "tuesday_13", :default => false
t.boolean "wednesday_13", :default => false
t.boolean "thursday_13", :default => false
t.boolean "friday_13", :default => false
t.boolean "saturday_13", :default => false
t.boolean "sunday_13", :default => false
t.boolean "monday_14", :default => false
t.boolean "tuesday_14", :default => false
t.boolean "wednesday_14", :default => false
t.boolean "thursday_14", :default => false
t.boolean "friday_14", :default => false
t.boolean "saturday_14", :default => false
t.boolean "sunday_14", :default => false
t.boolean "monday_15", :default => false
t.boolean "tuesday_15", :default => false
t.boolean "wednesday_15", :default => false
t.boolean "thursday_15", :default => false
t.boolean "friday_15", :default => false
t.boolean "saturday_15", :default => false
t.boolean "sunday_15", :default => false
t.boolean "monday_16", :default => false
t.boolean "tuesday_16", :default => false
t.boolean "wednesday_16", :default => false
t.boolean "thursday_16", :default => false
t.boolean "friday_16", :default => false
t.boolean "saturday_16", :default => false
t.boolean "sunday_16", :default => false
t.boolean "monday_17", :default => false
t.boolean "tuesday_17", :default => false
t.boolean "wednesday_17", :default => false
t.boolean "thursday_17", :default => false
t.boolean "friday_17", :default => false
t.boolean "saturday_17", :default => false
t.boolean "sunday_17", :default => false
t.boolean "monday_18", :default => false
t.boolean "tuesday_18", :default => false
t.boolean "wednesday_18", :default => false
t.boolean "thursday_18", :default => false
t.boolean "friday_18", :default => false
t.boolean "saturday_18", :default => false
t.boolean "sunday_18", :default => false
t.boolean "monday_19", :default => false
t.boolean "tuesday_19", :default => false
t.boolean "wednesday_19", :default => false
t.boolean "thursday_19", :default => false
t.boolean "friday_19", :default => false
t.boolean "saturday_19", :default => false
t.boolean "sunday_19", :default => false
t.boolean "monday_20", :default => false
t.boolean "tuesday_20", :default => false
t.boolean "wednesday_20", :default => false
t.boolean "thursday_20", :default => false
t.boolean "friday_20", :default => false
t.boolean "saturday_20", :default => false
t.boolean "sunday_20", :default => false
t.boolean "monday_21", :default => false
t.boolean "tuesday_21", :default => false
t.boolean "wednesday_21", :default => false
t.boolean "thursday_21", :default => false
t.boolean "friday_21", :default => false
t.boolean "saturday_21", :default => false
t.boolean "sunday_21", :default => false
t.boolean "monday_22", :default => false
t.boolean "tuesday_22", :default => false
t.boolean "wednesday_22", :default => false
t.boolean "thursday_22", :default => false
t.boolean "friday_22", :default => false
t.boolean "saturday_22", :default => false
t.boolean "sunday_22", :default => false
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
|
fjuan/padel
|
app/controllers/users_controller.rb
|
class UsersController < ApplicationController
def update
@user = current_user
respond_to do |format|
if @user.update_attributes(params[:user])
format.json { respond_with_bip(@user) }
else
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
end
|
bugkingK/RxPagingKit
|
RxPagingKit.podspec
|
#
# Be sure to run `pod lib lint StringStylizer.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "RxPagingKit"
s.version = "0.5.1"
s.summary = "Reactive Extension for PagingKit"
s.description = <<-DESC
You can implement the binding with Reactive Programming instead of Delegate pattern.
DESC
s.homepage = "https://github.com/kazuhiro4949/RxPagingKit"
s.license = 'MIT'
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/kazuhiro4949/RxPagingKit.git", :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.source_files = "RxPagingKit/*.{swift,h}"
s.dependency 'RxSwift', '~> 5'
s.dependency 'RxCocoa', '~> 5'
s.dependency 'PagingKit', '~> 1'
end
|
avinashtag/ZZPings
|
ZZPings.podspec
|
<reponame>avinashtag/ZZPings<filename>ZZPings.podspec
Pod::Spec.new do |s|
s.name = 'ZZPings'
s.version = '1.0'
s.summary = 'ZZPings return rtt and ttl for you and you are able to tell him the count of packets to send .'
#s.description = 'simple ping return rtt'
s.homepage = 'https://github.com/avinashtag/ZZPings'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<Avinash>' => '<<EMAIL>>' }
s.source = { :git => 'https://github.com/avinashtag/ZZPings.git', :tag => s.version.to_s }
s.source_files = 'ZZPings/*'
s.ios.deployment_target = '9.0'
end
|
allred/augur
|
app/controllers/welcome_controller.rb
|
class WelcomeController < ApplicationController
http_basic_authenticate_with name: "augur", password: "<PASSWORD>"
def index
tc = TwitterClient.new
@message_error = ''
@client = tc.client
if params[:mark_read]
begin
tweet = Tweet.find(params[:mark_read])
tweet.read = 1
tweet.save
rescue ActiveRecord::RecordNotFound
@message_error = 'Record Not Found'
end
end
if params[:u] && params[:u] != ''
twitter_user_id = nil
begin
@timeline = @client.user_timeline(params[:u])
@timeline.each do |t|
_ = Tweet.find_or_create_by(
tweet_id: t.id,
text: t.text,
user_id: t.user.id,
)
twitter_user_id = t.user.id
end
rescue Twitter::Error::Unauthorized
@message_error = 'Unauthorized'
end
@tweets_unread = Tweet.where(user_id: twitter_user_id, read: nil)
end
end
private
def index_params
params.require(:index).permit(:u, :mark_read)
end
end
|
allred/augur
|
app/models/tweet.rb
|
class Tweet < ApplicationRecord
end
|
allred/augur
|
lib/twitter_client.rb
|
<filename>lib/twitter_client.rb
require 'twitter'
class TwitterClient
attr_accessor :client
def initialize()
@client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY'] || 'jZFm6u2gUshTozg8VRdLtNq3M'
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
end
end
end
|
jayhendren/omnibus-software
|
config/software/curl.rb
|
#
# Copyright 2012-2018 Chef Software, Inc.
#
# 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.
#
name "curl"
default_version "7.63.0"
dependency "zlib"
dependency "openssl"
dependency "cacerts"
license "MIT"
license_file "COPYING"
skip_transitive_dependency_licensing true
version("7.63.0") { source sha256: "d483b89062832e211c887d7cf1b65c902d591b48c11fe7d174af781681580b41" }
version("7.59.0") { source sha256: "099d9c32dc7b8958ca592597c9fabccdf4c08cfb7c114ff1afbbc4c6f13c9e9e" }
version("7.56.0") { source sha256: "f1bc17a7e5662dbd8d4029750a6dbdb72a55cf95826a270ab388b05075526104" }
version("7.53.1") { source sha256: "64f9b7ec82372edb8eaeded0a9cfa62334d8f98abc65487da01188259392911d" }
version("7.51.0") { source sha256: "65b5216a6fbfa72f547eb7706ca5902d7400db9868269017a8888aa91d87977c" }
version("7.47.1") { source md5: "3f9d1be7bf33ca4b8c8602820525302b" }
version("7.36.0") { source md5: "643a7030b27449e76413d501d4b8eb57" }
source url: "https://curl.haxx.se/download/curl-#{version}.tar.gz"
relative_path "curl-#{version}"
build do
env = with_standard_compiler_flags(with_embedded_path)
if freebsd?
# from freebsd ports - IPv6 Hostcheck patch
patch source: "curl-freebsd-hostcheck.patch", plevel: 1, env: env
end
delete "#{project_dir}/src/tool_hugehelp.c"
if aix?
# alpn doesn't appear to work on AIX when connecting to certain sites, most
# importantly for us https://www.github.com Since git uses libcurl under
# the covers, this functionality breaks the handshake on connection, giving
# a cryptic error. This patch essentially forces disabling of ALPN on AIX,
# which is not really what we want in a http/2 world, but we're not there
# yet.
patch_env = env.dup
patch_env["PATH"] = "/opt/freeware/bin:#{env['PATH']}" if aix?
patch source: "curl-aix-disable-alpn.patch", plevel: 0, env: patch_env
# otherwise gawk will die during ./configure with variations on the theme of:
# "/opt/omnibus-toolchain/embedded/lib/libiconv.a(shr4.o) could not be loaded"
env["LIBPATH"] = "/usr/lib:/lib"
end
configure_options = [
"--prefix=#{install_dir}/embedded",
"--disable-manual",
"--disable-debug",
"--enable-optimize",
"--disable-ldap",
"--disable-ldaps",
"--disable-rtsp",
"--enable-proxy",
"--disable-dependency-tracking",
"--enable-ipv6",
"--without-libidn",
"--without-gnutls",
"--without-librtmp",
"--with-ssl=#{install_dir}/embedded",
"--with-zlib=#{install_dir}/embedded",
"--with-ca-bundle=#{install_dir}/embedded/ssl/certs/cacert.pem",
]
configure(*configure_options, env: env)
make "-j #{workers}", env: env
make "install", env: env
end
|
RKelln/riemann-ruby-client
|
lib/riemann/client/tcp.rb
|
require 'monitor'
require 'riemann/client/tcp_socket'
module Riemann
class Client
class TCP < Client
attr_accessor :host, :port, :socket
# Public: Set a socket factory -- an object responding
# to #call(options) that returns a Socket object
def self.socket_factory=(factory)
@socket_factory = factory
end
# Public: Return a socket factory
def self.socket_factory
@socket_factory || proc { |options| TcpSocket.connect(options) }
end
def initialize(options = {})
@options = options
@locket = Monitor.new
end
def socket
@locket.synchronize do
if @pid && @pid != Process.pid
close
end
if @socket and not @socket.closed?
return @socket
end
@socket = self.class.socket_factory.call(@options)
@pid = Process.pid
return @socket
end
end
def close
@locket.synchronize do
if @socket && !@socket.closed?
@socket.close
end
@socket = nil
end
end
def connected?
!@socket && @socket.closed?
end
# Read a message from a stream
def read_message(s)
if buffer = s.read(4) and buffer.size == 4
length = buffer.unpack('N').first
begin
str = s.read length
message = Riemann::Message.decode str
rescue => e
puts "Message was #{str.inspect}"
raise
end
unless message.ok
puts "Failed"
raise ServerError, message.error
end
message
else
raise InvalidResponse, "unexpected EOF"
end
end
def send_recv(message)
with_connection do |s|
s.write(message.encode_with_length)
read_message(s)
end
end
alias send_maybe_recv send_recv
# Yields a connection in the block.
def with_connection
tries = 0
@locket.synchronize do
begin
tries += 1
yield(socket)
rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, InvalidResponse, Timeout::Error, Riemann::Client::TcpSocket::Error
close
raise if tries > 3
retry
rescue Exception
close
raise
end
end
end
end
end
end
|
RKelln/riemann-ruby-client
|
lib/riemann/client/udp.rb
|
<reponame>RKelln/riemann-ruby-client<gh_stars>0
module Riemann
class Client
class UDP < Client
MAX_SIZE = 16384
attr_accessor :host, :port, :socket, :max_size
def initialize(opts = {})
@host = opts[:host] || HOST
@port = opts[:port] || PORT
@max_size = opts[:max_size] || MAX_SIZE
@locket = Mutex.new
end
def connect
@socket = UDPSocket.new
end
def close
@locket.synchronize do
@socket.close
end
end
def connected?
!!@socket && @socket.closed?
end
# Read a message from a stream
def read_message(s)
raise Unsupported
end
def send_recv(*a)
raise Unsupported
end
def send_maybe_recv(message)
with_connection do |s|
x = message.encode ''
unless x.length < @max_size
raise TooBig
end
s.send(x, 0, @host, @port)
nil
end
end
# Yields a connection in the block.
def with_connection
tries = 0
@locket.synchronize do
begin
tries += 1
yield(@socket || connect)
rescue IOError => e
raise if tries > 3
connect and retry
rescue Errno::EPIPE => e
raise if tries > 3
connect and retry
rescue Errno::ECONNREFUSED => e
raise if tries > 3
connect and retry
rescue Errno::ECONNRESET => e
raise if tries > 3
connect and retry
rescue InvalidResponse => e
raise if tries > 3
connect and retry
end
end
end
end
end
end
|
t9md/atom-open-this
|
spec/fixtures/top.rb
|
# dir1/dir1
require "./dir1/dir1"
# dir1/file1
# dir1/file2
|
icco/elb_processor
|
download.rb
|
require "rubygems"
require "bundler"
Bundler.require(:default, ENV["RACK_ENV"] || :development)
require 'fileutils'
def percentile(values, percentile)
raise "Percentile must be < 1." if percentile > 1
values_sorted = values.sort
k = (percentile*(values_sorted.length-1)+1).floor - 1
f = (percentile*(values_sorted.length-1)+1).modulo(1)
return values_sorted[k] + (f * (values_sorted[k+1] - values_sorted[k]))
end
# Other ideas: https://gist.github.com/meinside/9461552
year = 2015
month = 8
prefix = "web-railsapp-production/AWSLogs/894935469341/elasticloadbalancing/us-east-1/#{year}/#{'%02i' % month}"
# ELB Log Format
# timestamp elb client:port backend:port request_processing_time backend_processing_time response_processing_time elb_status_code backend_status_code received_bytes sent_bytes "request" "user_agent" ssl_cipher ssl_protocol
# "2015-07-31T23:59:59.852432Z web-railsapp-production 192.168.127.12:27548 172.30.1.199:80 0.000052 0.078216 0.000036 200 200 220 2 \"POST http://littlebits.cc:80/ahoy/events HTTP/1.1\" \"Mozilla/5.0 (iPad; CPU OS 8_4 like
# http://httpd.apache.org/docs/2.2/mod/mod_log_config.html
format = '%t %{ELB}n %a:{remote}p %A:{local}p %{request_processing_time}n %{backend_processing_time}n %{response_processing_time}n %{elb_status_code}n %{backend_status_code}n %{received_bytes}n %{sent_bytes}n \"%r\" \"%{User-Agent}i\" - -'
parser = ApacheLogRegex.new(format)
service = Fog::Storage.new({:provider => 'AWS', :aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'], :aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']})
dir = service.directories.get("littlebits-logs")
files = Fog::Storage::AWS::Files.new(directory: dir, service: service, prefix: prefix, max_keys: 10000)
request_data = Hash.new { |h, k| h[k] = [] }
files.each do |s3_file|
puts " - Parsing #{s3_file.key}"
if !File.exist? s3_file.key
dirname = File.dirname(s3_file.key)
unless File.directory?(dirname)
FileUtils.mkdir_p(dirname)
end
File.open(s3_file.key, 'w') do |local_file|
local_file.write(s3_file.body)
end
end
File.open(s3_file.key, "r").each_line do |l|
data, request, user_data = l.encode('UTF-8', :invalid => :replace).split('"').delete_if {|i| i == " " }
data = data.split " "
time = Chronic.parse(data[0]) # "2015-08-01T00:00:48.828256Z"
elb = data[1] # "web-railsapp-production"
source = data[2] # "172.16.58.3:27442"
backend = data[3] # "172.30.1.51:80"
request_processing_time = data[4].to_f # "0.000045"
backend_processing_time = data[5].to_f # "0.766932"
response_processing_time = data[6].to_f # "0.000044"
elb_status_code = data[7].to_i # "200"
backend_status_code = data[8].to_i # "200"
received_bytes = data[9].to_i # "0"
sent_bytes = data[10].to_i # "20219"
request_data[request] << backend_processing_time
end
more_than_ten = request_data.select {|k,v| v.size > 100 }
more_than_ten.to_a.map {|k,v| [k, percentile(v, 0.90)] }.sort {|a,b| a[1] <=> b[1] }.each do |k, v|
puts "#{k} \t => \t #{v}"
end
end
more_than_ten = request_data.select {|k,v| v.size > 10 }
more_than_ten.to_a.map {|k,v| [k, percentile(v, 0.90)] }.sort {|a,b| a[1] <=> b[1] }.each do |k, v|
puts "#{k} \t => \t #{v}"
end
|
yanske1/DramaNow
|
server/app/services/create_watch_list_service.rb
|
class CreateWatchListService
def initialize(user)
@user = user
end
def create
watched_dramas = @user.user_dramas.eager_load(:drama, :watching_events).to_a
# Get latest user_drama per drama
latest_user_dramas_by_drama = watched_dramas.each_with_object({}) do |user_drama, hash|
drama = user_drama.drama
unless hash.key?(drama.id) && hash[drama.id].episode_number > user_drama.episode_number
hash[drama.id] = user_drama
end
end
list = latest_user_dramas_by_drama.map do |_, user_drama|
if user_drama.latest_watching_event.still_watching?
create_list_object(user_drama)
elsif user_drama.new_episode_available?
create_list_object(user_drama, true)
end
end
list.compact
end
private
def create_list_object(user_drama, next_episode = false)
episode_number = next_episode ? user_drama.episode_number + 1 : user_drama.episode_number
link = user_drama.drama.link_to_episode(episode_number)
timestamp = next_episode ? 0 : user_drama.latest_watching_event.duration
{
title: user_drama.drama.pretty_title,
episode: episode_number,
link: link,
img: user_drama.drama.thumbnail,
timestamp: timestamp,
}
end
end
|
yanske1/DramaNow
|
server/test/models/drama_test.rb
|
require 'test_helper'
class DramaTest < ActiveSupport::TestCase
test "drama can only be created on supported sites" do
invalid_site = "not_a_site_dot_com"
refute_includes Drama::ACCEPTED_SITES, invalid_site
drama_one = dramas(:one)
drama_one.site = invalid_site
refute drama_one.save
assert_equal drama_one.errors.full_messages, ["Site is not included in the list"]
end
test "no duplicate dramas on same site can be saved" do
drama_one = dramas(:one)
dup_drama = drama_one.dup
refute dup_drama.save
assert_equal dup_drama.errors.full_messages, ["Title already exists in selected site"]
end
test "modifying latest_episode automatically sets the timestamp" do
drama_one = dramas(:one)
time = 2.days.from_now
Timecop.freeze(time) do
drama_one.update!(latest_episode: 100)
assert_equal drama_one.latest_episode_update.to_i, time.to_i
end
end
test "modifying fields not latest_episode does not sets the timestamp" do
drama_one = dramas(:one)
time = 2.days.from_now
Timecop.freeze(time) do
drama_one.link = "123"
drama_one.save!
refute_equal drama_one.latest_episode_update.to_i, time.to_i
end
end
test "link_to_episode returns correct link for dramafever sites" do
drama_one = dramas(:one)
drama_one.update!(link: 'https://www.dramafever.com/drama/123/28/slug-me/')
assert_equal drama_one.link_to_episode(10),
"https://www.dramafever.com/drama/123/10/slug-me/"
end
test "active scope returns dramas with latest episode updated within 35 days" do
drama_one = dramas(:one)
drama_one.update_column(:latest_episode_update, 30.days.ago)
drama_two = dramas(:two)
drama_two.update_column(:latest_episode_update, 40.days.ago)
assert_equal Drama.active.map(&:id), [drama_one.id]
end
test "pretty title returns unslugged, capitalized, trimed title" do
drama = dramas(:one)
drama.title = "a-very-good-test-case-for-a-test-"
assert_equal drama.pretty_title, "A Very Good Test Case for a Test"
end
end
|
yanske1/DramaNow
|
server/db/migrate/20180817033842_set_null_to_dramas.rb
|
class SetNullToDramas < ActiveRecord::Migration[5.1]
def change
change_column :dramas, :title, :string, :null => false
change_column :dramas, :site, :string, :null => false
change_column :dramas, :link, :string, :null => false
change_column :dramas, :latest_episode, :integer, :default => 0
end
end
|
yanske1/DramaNow
|
server/config/routes.rb
|
Rails.application.routes.draw do
resources :users, only: :create, constraints: { format: 'json' } do
get 'valid', on: :collection
get 'watch_list', on: :member
resources :watching_events, only: :create
end
end
|
yanske1/DramaNow
|
server/app/services/create_watching_event_service.rb
|
class CreateWatchingEventService
def initialize(params)
@user_key = params[:user_id]
@url = params[:url]
@title = params[:title]
@site = params[:site]
@thumbnail = params[:thumbnail]
@current_episode = params[:currentEpisode]
@current_time = params[:currentTime]
@episode_length = params[:episodeLength]
@latest_episode = params[:latestEpisode]
end
# Returns true if create is sucessful, else false
def create
@user = User.find_by(key: @user_key)
return false if @user.nil?
@drama = Drama.find_by(title: @title, site: @site) || create_drama
@userdrama = UserDrama.find_by(
user: @user,
drama: @drama,
episode_number: @current_episode
) || create_user_drama
update_latest_episode
watching_event = WatchingEvent.new(
user_drama: @userdrama,
duration: @current_time
)
return watching_event.save
end
private
def create_drama
Drama.create!(
title: @title,
site: @site,
latest_episode: @latest_episode,
latest_episode_update: Time.current,
link: @url,
thumbnail: @thumbnail
)
end
def create_user_drama
UserDrama.create!(
user: @user,
drama: @drama,
episode_number: @current_episode,
episode_length: @episode_length
)
end
def update_latest_episode
if @latest_episode > @drama.latest_episode
@drama.update!(latest_episode: @latest_episode)
end
end
end
|
yanske1/DramaNow
|
server/db/migrate/20180812205125_set_null_to_key.rb
|
class SetNullToKey < ActiveRecord::Migration[5.1]
def change
change_column :users, :key, :string, :null => false
end
end
|
yanske1/DramaNow
|
server/test/controllers/users_controller_test.rb
|
require 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
setup do
@stub_list_response = [{
title: "slug-me",
episode: 2,
link: "https://www.dramafever.com/drama/123/2/slug-me/",
img: "www.img.com",
timestamp: 10,
}]
end
test "create does not respond to html" do
assert_raise ActionController::UnknownFormat do
post users_url, params: { format: :html }
end
end
test "create creates user and respond with key" do
assert_difference 'User.count', 1 do
post users_url, params: { format: :json }
assert_response :success
end
new_key = User.last.key
assert_equal new_key, response.body
end
test "valid does not respond to html" do
assert_raise ActionController::UnknownFormat do
get valid_users_url, params: { key: "123456", format: :html }
end
end
test "valid returns ok if user exists" do
user_one = users(:one)
get valid_users_url, params: { key: user_one.key, format: :json }
assert_response :ok
end
test "valid returns not_found if user does not exist" do
invalid_key = "!!!!!!"
refute User.exists?(key: invalid_key)
get valid_users_url, params: { key: invalid_key, format: :json }
assert_response :not_found
end
test "valid returns not_found if user key is not passed" do
get valid_users_url, params: { format: :json }
assert_response :not_found
end
test "watch list returns list if user key exists" do
user = users(:one)
CreateWatchListService.any_instance.expects(:create).returns(@stub_list_response).once
get watch_list_user_url(user.key), params: { format: :json }
assert_response :ok
assert_equal response.body, @stub_list_response.to_json
end
test "watch list returns not_found if user key does not exist" do
invalid_key = "!!!!!!"
refute User.exists?(key: invalid_key)
get watch_list_user_url(invalid_key), params: { format: :json }
assert_response :not_found
end
end
|
yanske1/DramaNow
|
server/app/models/watching_event.rb
|
class WatchingEvent < ApplicationRecord
belongs_to :user_drama
validates :user_drama, presence: true
validates :duration, presence: true, numericality: { only_integer: true }
default_scope { order(duration: :asc) }
def still_watching?
return user_drama.episode_length - duration > 5.minutes.to_i
end
end
|
yanske1/DramaNow
|
server/app/controllers/watching_events_controller.rb
|
<reponame>yanske1/DramaNow
class WatchingEventsController < ApplicationController
# POST /users/:user_id/watching_events.json
def create
create_watching_event = CreateWatchingEventService.new(watching_event_params)
respond_to do |format|
if create_watching_event.create
format.json { render json: "Success", status: :created }
else
format.json { render json: "Failure to create watching event", status: :unprocessable_entity }
end
end
end
private
def watching_event_params
params.permit(
:user_id,
:url,
:title,
:site,
:thumbnail,
:currentEpisode,
:currentTime,
:episodeLength,
:latestEpisode
).to_h || {}
end
end
|
yanske1/DramaNow
|
server/test/services/create_watch_list_service_test.rb
|
<gh_stars>0
require 'test_helper'
class CreateWatchListServiceTest < ActiveSupport::TestCase
setup do
@user = User.create!
@service = CreateWatchListService.new(@user)
@watching_event_service_params_episode_one = {
user_id: @user.key,
url: "https://www.dramafever.com/drama/123/1/slug-me/",
title: "slug-me",
site: "dramafever",
thumbnail: "www.img.com",
currentEpisode: 1,
currentTime: 1,
episodeLength: 1.hours.to_i,
latestEpisode: 30
}
@watching_event_service_params_episode_two = {
user_id: @user.key,
url: "https://www.dramafever.com/drama/123/2/slug-me/",
title: "slug-me",
site: "dramafever",
thumbnail: "www.img.com",
currentEpisode: 2,
currentTime: 10,
episodeLength: 1.hours.to_i,
latestEpisode: 30
}
@expected_list = [{
title: "Slug Me",
episode: 2,
link: "https://www.dramafever.com/drama/123/2/slug-me/",
img: "www.img.com",
timestamp: 10,
}]
end
test "returns episodes currently being watched" do
# Setup: 2 events for episode one, finished watching, 1 event for episode two
CreateWatchingEventService.new(@watching_event_service_params_episode_one).create
@watching_event_service_params_episode_one[:currentTime] = 1.hours.to_i
CreateWatchingEventService.new(@watching_event_service_params_episode_one).create
CreateWatchingEventService.new(@watching_event_service_params_episode_two).create
assert_equal @service.create, @expected_list
end
test "does not returns episodes that are not available" do
# Setup: 1 event at end of episode one, drama only has 1 episode
@watching_event_service_params_episode_one[:currentTime] = 1.hours.to_i
@watching_event_service_params_episode_one[:latestEpisode] = 1
CreateWatchingEventService.new(@watching_event_service_params_episode_one).create
assert_equal @service.create, []
end
test "returns new episodes that are available" do
# Setup: 1 event at end of epside one, drama has more than 1 episode
@watching_event_service_params_episode_one[:currentTime] = 1.hours.to_i
CreateWatchingEventService.new(@watching_event_service_params_episode_one).create
@expected_list.first[:timestamp] = 0
assert_equal @service.create, @expected_list
end
end
|
yanske1/DramaNow
|
server/db/schema.rb
|
<filename>server/db/schema.rb
# 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: 20180817162721) do
create_table "dramas", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "title", null: false
t.string "site", null: false
t.integer "latest_episode", default: 0
t.timestamp "latest_episode_update"
t.string "link", null: false
t.string "thumbnail"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["title", "site"], name: "index_on_title_and_site"
end
create_table "user_dramas", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.bigint "user_id", null: false
t.bigint "drama_id", null: false
t.integer "episode_number", null: false
t.integer "episode_length", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["drama_id"], name: "index_user_dramas_on_drama_id"
t.index ["user_id", "drama_id", "episode_number"], name: "index_on_user_and_drama_and_episode"
t.index ["user_id", "drama_id"], name: "index_on_user_and_drama"
t.index ["user_id"], name: "index_user_dramas_on_user_id"
end
create_table "users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "key", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["key"], name: "index_users_on_key", unique: true
end
create_table "watching_events", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.bigint "user_drama_id", null: false
t.integer "duration", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_drama_id"], name: "index_watching_events_on_user_drama_id"
end
add_foreign_key "user_dramas", "dramas"
add_foreign_key "user_dramas", "users"
add_foreign_key "watching_events", "user_dramas"
end
|
yanske1/DramaNow
|
server/app/models/user.rb
|
class User < ApplicationRecord
has_many :user_dramas, dependent: :destroy
validates :key, presence: true, uniqueness: true, length: { is: 6 }
after_initialize :intialize_unique_key
private
def intialize_unique_key
# While not unqiue, re-initialize
while self.key.nil?
key = SecureRandom.urlsafe_base64[0, 6]
self.key = key unless User.where(key: self.key).exists?
end
end
end
|
yanske1/DramaNow
|
server/app/controllers/application_controller.rb
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
before_action :destroy_session
def destroy_session
request.session_options[:skip] = true
end
end
|
yanske1/DramaNow
|
server/test/models/user_drama_test.rb
|
<reponame>yanske1/DramaNow<gh_stars>0
require 'test_helper'
class UserDramaTest < ActiveSupport::TestCase
test "user drama must belong to an existing user" do
user_dramas(:one).user.destroy!
userdrama = user_dramas(:one).dup
refute userdrama.save
assert_includes userdrama.errors.full_messages, "User must exist"
end
test "user drama must belong to an existing drama" do
user_dramas(:one).drama.destroy!
userdrama = user_dramas(:one).dup
refute userdrama.save
assert_includes userdrama.errors.full_messages, "Drama must exist"
end
test "user drama validates uniqueness on user, drama and episode number" do
userdrama = user_dramas(:one).dup
refute userdrama.save
assert_includes userdrama.errors.full_messages, "User already watching this episode"
end
test "new episode returns true if new episode is available" do
userdrama = user_dramas(:one)
drama = userdrama.drama
drama.update!(latest_episode: userdrama.episode_number + 1)
assert_predicate userdrama.reload, :new_episode_available?
end
test "new episode returns false if new episode is not available" do
userdrama = user_dramas(:one)
drama = userdrama.drama
drama.update!(latest_episode: userdrama.episode_number)
refute_predicate userdrama.reload, :new_episode_available?
drama.update!(latest_episode: userdrama.episode_number - 1)
refute_predicate userdrama.reload, :new_episode_available?
end
end
|
yanske1/DramaNow
|
server/test/jobs/scrape_dramas_job_test.rb
|
require 'test_helper'
class ScrapeDramasJobTest < ActiveJob::TestCase
setup do
@drama = dramas(:one).dup
Drama.destroy_all
end
test "scrapes dramafever sites" do
@drama.site = Drama::DRAMAFEVER
@drama.latest_episode = 1
@drama.link = "https://www.dramafever.com/drama/5195/28/legend-of-fuyao-/"
@drama.save!
ScrapeDramasJob.perform_now
assert_equal @drama.reload.latest_episode, 66
end
end
|
yanske1/DramaNow
|
server/app/jobs/scrape_dramas_job.rb
|
require 'nokogiri'
require "watir"
class ScrapeDramasJob < ApplicationJob
queue_as :default
def perform(*args)
active_dramas = Drama.active
active_dramas.each do |drama|
doc = open_browser(drama.link)
case drama.site
when Drama::DRAMAFEVER
latest_episode = parse_dramafever_site(doc)
update_drama(latest_episode, drama)
end
end
end
private
def open_browser(url)
browser = Watir::Browser.new(:chrome, headless: true)
browser.goto(url)
Nokogiri::HTML.parse(browser.html)
end
def parse_dramafever_site(doc)
# Check which one's value contains "TOTAL_EPISODES"
content = doc.css('h5').detect do |elem|
elem.values.include?("TOTAL_EPISODES")
end&.children&.text
return 0 if content.nil?
# Expected: "## episodes"
space_index = content.index(' ')
return content[0..space_index - 1].to_i
end
def update_drama(latest_episode, drama)
if latest_episode > drama.latest_episode
drama.update!(latest_episode: latest_episode)
end
end
end
|
yanske1/DramaNow
|
server/test/services/create_watching_event_service_test.rb
|
require 'test_helper'
class CreateWatchingEventServiceTest < ActiveSupport::TestCase
setup do
@user = users(:one)
@drama = dramas(:one)
@userdrama = user_dramas(:one)
@create_watching_event_params = {
user_id: @user.key,
url: "www.dummy.link",
title: @drama.title,
site: @drama.site,
thumbnail: @drama.thumbnail,
currentEpisode: @userdrama.episode_number,
currentTime: 1,
episodeLength: @userdrama.episode_length,
latestEpisode: @drama.latest_episode
}
end
test "creates a watching event with existing drama and userdrama " do
create_watching_event = CreateWatchingEventService.new(@create_watching_event_params)
assert_no_difference 'Drama.count' do
assert_no_difference 'UserDrama.count' do
assert_difference 'WatchingEvent.count', 1 do
assert create_watching_event.create
end
end
end
event = WatchingEvent.unscoped.last
assert_equal event.user_drama_id, @userdrama.id
assert_equal event.duration, @create_watching_event_params[:currentTime]
end
test "creates a drama and userdrama if no drama present" do
@drama.destroy!
create_watching_event = CreateWatchingEventService.new(@create_watching_event_params)
assert_difference 'Drama.count', 1 do
assert_difference 'UserDrama.count', 1 do
assert_difference 'WatchingEvent.count', 1 do
assert create_watching_event.create
end
end
end
new_drama = Drama.last
assert_equal new_drama.title, @create_watching_event_params[:title]
assert_equal new_drama.site, @create_watching_event_params[:site]
refute_nil new_drama.latest_episode_update
end
test "does not create anything if user does not exist" do
@user.destroy!
create_watching_event = CreateWatchingEventService.new(@create_watching_event_params)
assert_no_difference 'Drama.count' do
assert_no_difference 'UserDrama.count' do
assert_no_difference 'WatchingEvent.count' do
refute create_watching_event.create
end
end
end
end
test "creates a userdrama if no userdrama present" do
@userdrama.destroy!
create_watching_event = CreateWatchingEventService.new(@create_watching_event_params)
assert_no_difference 'Drama.count' do
assert_difference 'UserDrama.count', 1 do
assert_difference 'WatchingEvent.count', 1 do
assert create_watching_event.create
end
end
end
new_user_drama = UserDrama.unscoped.last
assert_equal new_user_drama.drama_id, @drama.id
assert_equal new_user_drama.user_id, @user.id
assert_equal new_user_drama.episode_number, @create_watching_event_params[:currentEpisode]
end
end
|
yanske1/DramaNow
|
server/db/migrate/20180817033552_create_dramas.rb
|
<gh_stars>0
class CreateDramas < ActiveRecord::Migration[5.1]
def change
create_table :dramas do |t|
t.string :title
t.string :site
t.integer :latest_episode
t.timestamp :latest_episode_update
t.string :link
t.string :thumbnail
t.timestamps
end
add_index :dramas, [:title, :site], name: 'index_on_title_and_site'
end
end
|
yanske1/DramaNow
|
server/app/controllers/users_controller.rb
|
class UsersController < ApplicationController
# POST /users.json
def create
@user = User.new
respond_to do |format|
if @user.save
format.json { render json: @user.key, status: :created }
else
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# GET /users/valid.json
def valid
user_exists = if params.key?(:key)
User.exists?(key: params[:key])
end
respond_to do |format|
if user_exists
format.json { render json: "Valid", status: :ok }
else
format.json { render json: "", status: :not_found }
end
end
end
# GET /users/:id/watch_list.json
def watch_list
user = User.find_by(key: params[:id])
respond_to do |format|
if user
watch_list = CreateWatchListService.new(user).create
format.json { render json: watch_list, status: :ok }
else
format.json { render json: "", status: :not_found }
end
end
end
end
|
yanske1/DramaNow
|
server/db/migrate/20180817153935_create_user_dramas.rb
|
class CreateUserDramas < ActiveRecord::Migration[5.1]
def change
create_table :user_dramas do |t|
t.references :user, foreign_key: true, null: false
t.references :drama, foreign_key: true, null: false
t.integer :episode_number, null: false
t.integer :episode_length, null: false
t.timestamps
end
add_index :user_dramas, [:user_id, :drama_id], name: 'index_on_user_and_drama'
add_index :user_dramas, [:user_id, :drama_id, :episode_number], name: 'index_on_user_and_drama_and_episode'
# Indexed on user by default by relation
end
end
|
yanske1/DramaNow
|
server/test/models/user_test.rb
|
<gh_stars>0
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "should intialize user with key length 6" do
user = User.new
assert_predicate user.key, :present?
assert_equal user.key.length, 6
user.save!
end
test "should not create user with non unique key" do
user_one = User.create!
user_two = User.new
user_two.key = user_one.key
refute user_two.save
assert_equal user_two.errors.full_messages, ["Key has already been taken"]
end
end
|
yanske1/DramaNow
|
server/test/controllers/watching_events_controller_test.rb
|
require 'test_helper'
class WatchingEventsControllerTest < ActionDispatch::IntegrationTest
test "create does not respond to html" do
assert_raise ActionController::UnknownFormat do
post user_watching_events_url("123"), params: { format: :html }
end
end
test "return created if watching event created" do
CreateWatchingEventService.any_instance.expects(:create).returns(true).once
post user_watching_events_url("123"), params: { format: :json }
assert_response :created
end
test "return unprocessable if watching event creation failed" do
CreateWatchingEventService.any_instance.expects(:create).returns(false).once
post user_watching_events_url("123"), params: { format: :json }
assert_response :unprocessable_entity
end
end
|
yanske1/DramaNow
|
server/config/initializers/scheduler.rb
|
<filename>server/config/initializers/scheduler.rb
require 'rufus-scheduler'
scheduler = Rufus::Scheduler.singleton
scheduler.every '4h' do
ScrapeDramasJob.perform_now
end
|
yanske1/DramaNow
|
server/app/models/user_drama.rb
|
<filename>server/app/models/user_drama.rb
class UserDrama < ApplicationRecord
# Represents an episode that a user is watching
belongs_to :user
belongs_to :drama
has_many :watching_events, dependent: :destroy
validates :user, presence: true
validates :drama, presence: true
validates :episode_number, presence: true, numericality: { only_integer: true }
validates :episode_length, presence: true, numericality: { only_integer: true }
validate :unique_user_drama_episode_number, on: :create
default_scope { order(episode_number: :asc) }
def new_episode_available?
return drama.latest_episode > episode_number
end
def latest_watching_event
watching_events.order(:duration).last
end
private
def unique_user_drama_episode_number
if UserDrama.where(user: self.user, drama: self.drama, episode_number: self.episode_number).exists?
errors.add(:user, "already watching this episode")
end
end
end
|
yanske1/DramaNow
|
server/app/models/drama.rb
|
<reponame>yanske1/DramaNow
class Drama < ApplicationRecord
include ActiveModel::Dirty
has_many :user_dramas, dependent: :destroy
DRAMAFEVER = 'dramafever'
ACCEPTED_SITES = [DRAMAFEVER].freeze
validates :title, presence: true, format: { with: /\A[a-zA-Z0-9-]+\Z/ }
validates :site, presence: true, inclusion: { in: ACCEPTED_SITES }
validates :link, presence: true
validates :latest_episode, presence: true, numericality: { only_integer: true }
validates :latest_episode_update, presence: true
validate :unique_title_and_site, on: :create
before_validation :update_latest_episode_timestamp
scope :active, -> { where('latest_episode_update > ? ', DateTime.now - 35.days) }
def link_to_episode(episode_number)
case site
when DRAMAFEVER
return link_to_dramafever_episode(episode_number)
end
end
def pretty_title
self.title.gsub('-', ' ').titleize.strip
end
private
def link_to_dramafever_episode(episode_number)
# URL format: https://www.dramafever.com/drama/[drama #]/[episode #]/[drama-slug]/
# Find index of / between [episode #], and replace with episode_number
split_link = link.split('/')
split_link[5] = episode_number
split_link.join('/') + '/'
end
def unique_title_and_site
if Drama.where(title: self.title, site: self.site).exists?
errors.add(:title, "already exists in selected site")
end
end
def update_latest_episode_timestamp
self.latest_episode_update = Time.current if latest_episode_changed?
end
end
|
yanske1/DramaNow
|
server/test/models/watching_event_test.rb
|
require 'test_helper'
class WatchingEventTest < ActiveSupport::TestCase
test "watching event must belong to existing user drama" do
watching_event = watching_events(:one).dup
watching_event.user_drama_id = 0
refute watching_event.save
assert_includes watching_event.errors.full_messages, "User drama must exist"
end
test "duration must be present in watching event" do
watching_event = watching_events(:one).dup
watching_event.duration = nil
refute watching_event.save
assert_includes watching_event.errors.full_messages, "Duration can't be blank"
end
test "still watching returns false if within 5 mins of end" do
watching_event = watching_events(:one)
watching_event.update!(duration: 0)
watching_event.user_drama.update!(episode_length: 5.minutes.to_i)
refute_predicate watching_event, :still_watching?
end
test "still watching returns true if within 5 mins of end" do
watching_event = watching_events(:one)
watching_event.update!(duration: 0)
watching_event.user_drama.update!(episode_length: 5.minutes.to_i + 1)
assert_predicate watching_event, :still_watching?
end
end
|
twp88/primus
|
spec/primus_spec.rb
|
<gh_stars>0
require 'spec_helper'
describe Hashify do
subject { Hashify }
context 'when passing primus a long hash' do
let(:long_hash) do
{
'a' => 'This',
'b' => 'is',
'c' => 'a',
'd' => 'longish',
'e' => 'hash',
'f' => 'for',
'g' => 'testing',
'h' => 'purposes',
'i' => '!'
}
end
it 'returns a reverse ordered capitlized string' do
expect(subject.call(long_hash)).to eq 'HFDB'
end
end
context 'when passing primus a short hash' do
let(:short_hash) { { 'a' => 'Indeed', 'b' => 'a', 'c' => 'short_hash' } }
it 'returns one capitlized letter' do
expect(subject.call(short_hash)).to eq 'B'
end
end
context 'when passing primus an empty hash' do
let(:empty_hash) { {} }
it 'returns an error message' do
expect { subject.call(empty_hash) }
.to raise_error(RuntimeError, 'This hash is empty')
end
end
end
|
twp88/primus
|
no_new.rb
|
<gh_stars>0
require './lib/primus'
include Primus
hash = { 'a' => 1, 'b' => 2, 'c' => 3 }
puts call(hash)
|
twp88/primus
|
lib/primus.rb
|
# frozen_string_literal: true
require 'primus/version'
# Takes a hash and returns string of reverse order odd keys
class Hashify
def self.call(hash)
raise 'This hash is empty' if hash.empty?
array = hash.each_with_index.map { |(key), index| key.upcase if index.odd? }.compact
array.sort.reverse.join('')
end
end
# add rubo cop, frozen string, revise sort each with index, each_slice,
# slice_each, call this without caiing .new
|
vicki29644/Super_hero_cli
|
lib/cli.rb
|
Class Cli
def run
puts "Cli class loaded"
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.