text
stringlengths
10
2.61M
# # Authors: Jeff Watts(jwatts@redhat.com) and Lucy Kerner(lkerner@redhat.com) # # # Method Code Goes here # $evm.log("info", "SCAP Schedule Start") require 'rubygems' require 'net/ssh' require 'rest_client' require "xmlrpc/client" require 'time' def log(level, msg, update_message = false) $evm.log(level, "#{msg}") @task.message = msg if @task && (update_message || level == 'error') end def latestsatelliteresultID (satelliteresults, profile) max_xID=-1 $evm.log("info", "Printing SCAP SatResults: #{satelliteresults}") satelliteresults.each do |satelliteresult| $evm.log("info", "SCAP Profile: #{satelliteresult["profile"]} \t xid = #{satelliteresult["xid"]} max so far #{max_xID}\t ") if profile==satelliteresult["profile"] currentxID=satelliteresult["xid"] if currentxID > max_xID max_xID=currentxID end end end return max_xID end #SERVICENOW CODE def call_servicenow(action, tablename='incident', body=nil) require 'rest_client' require 'json' require 'base64' servername = nil || $evm.object['servername'] username = nil || $evm.object['username'] password = nil || $evm.object.decrypt('password') url = "https://#{servername}/api/now/table/#{tablename}" params = { :method=>action, :url=>url, :headers=>{ :content_type=>:json, :accept=>:json, :authorization => "Basic #{Base64.strict_encode64("#{username}:#{password}")}" } } params[:payload] = body.to_json log(:info, "Calling url: #{url} action: #{action} payload: #{params[:payload]}") snow_response = RestClient::Request.new(params).execute log(:info, "response headers: #{snow_response.headers}") log(:info, "response code: #{snow_response.code}") log(:info, "response: #{snow_response}") snow_response_hash = JSON.parse(snow_response) return snow_response_hash['result'] end # create_vm_incident def build_vm_body(vm) comments = "VM: #{vm.name}\n" comments += "Hostname: #{vm.hostnames.first}\n" unless vm.hostnames.nil? comments += "Guest OS Description: #{vm.hardware.guest_os_full_name.inspect}\n" unless vm.hardware.guest_os_full_name.nil? comments += "IP Address: #{vm.ipaddresses}\n" comments += "Provider: #{vm.ext_management_system.name}\n" unless vm.ext_management_system.nil? comments += "Cluster: #{vm.ems_cluster.name}\n" unless vm.ems_cluster.nil? comments += "Host: #{vm.host.name}\n" unless vm.host.nil? comments += "CloudForms Server: #{$evm.root['miq_server'].hostname}\n" comments += "Region Number: #{vm.region_number}\n" comments += "vCPU: #{vm.num_cpu}\n" comments += "vRAM: #{vm.mem_cpu}\n" comments += "Disks: #{vm.num_disks}\n" comments += "Power State: #{vm.power_state}\n" comments += "Storage Name: #{vm.storage_name}\n" comments += "Allocated Storage: #{vm.allocated_disk_storage}\n" comments += "Provisioned Storage: #{vm.provisioned_storage}\n" comments += "GUID: #{vm.guid}\n" comments += "Tags: #{vm.tags.inspect}\n" (body_hash ||= {})['comments'] = comments return body_hash end begin $evm.root.attributes.sort.each { |k, v| $evm.log(:info, "Root:<$evm.root> Attribute - #{k}: #{v}")} object = $evm.root[$evm.root['vmdb_object_type']] case $evm.root['vmdb_object_type'] when 'vm' body_hash = build_vm_body(object) when 'host' body_hash = build_host_body(object) else raise "Invalid $evm.root['vmdb_object_type']: #{object}" end unless body_hash.nil? # object_name = 'Event' means that we were triggered from an Alert if $evm.root['object_name'] == 'Event' $evm.log(:info, "Detected Alert driven event") body_hash['short_description'] = "#{$evm.root['vmdb_object_type']}: #{object.name} - #{$evm.root['miq_alert_description']}" elsif $evm.root['ems_event'] # ems_event means that were triggered via Control Policy $evm.log(:info, "Detected Policy driven event") $evm.log(:info, "Inspecting $evm.root['ems_event']:<#{$evm.root['ems_event'].inspect}>") body_hash['short_description'] = "#{$evm.root['vmdb_object_type']}: #{object.name} - #{$evm.root['ems_event'].event_type}" else unless $evm.root['dialog_miq_alert_description'].nil? $evm.log(:info, "Detected service dialog driven event") # If manual creation add dialog input notes to body_hash body_hash['short_description'] = "#{$evm.root['vmdb_object_type']}: #{object.name} - #{$evm.root['dialog_miq_alert_description']}" else $evm.log(:info, "Detected manual driven event") # If manual creation add default notes to body_hash body_hash['short_description'] = "#{$evm.root['vmdb_object_type']}: #{object.name} - Incident manually created" end end end end #We can only work with a VM that's powered on vm = $evm.root['vm'] if vm.power_state == "off" $evm.log("info", "SCAP - VM not powered on") exit MIQ_ABORT end #Definitions for the Satellite @SATELLITE_URL = "http://" + $evm.object['satellite_ip'] + "/rpc/api" @SATELLITE_LOGIN = $evm.object['satellite_user'] @SATELLITE_PASSWORD = $evm.object.decrypt('satellite_password') #Get the chosen SCAP profile #profile = $evm.root['dialog_SCAP_Profiles'] profile = $evm.root['dialog_SCAPProfiles'] @PROFILE = "--profile " + "#{profile}" $evm.log("info", "SCAP - Profile: #{@PROFILE}") if @PROFILE == "--profile " $evm.log("info", "SCAP - Exit, no profile") exit MIQ_OK end #Definitions for the client; it would be better if I could get the domain name if vm.vendor_display == 'RedHat' theserver = "#{vm.name}" end if vm.vendor_display == 'VMware' theserver = "#{vm.hostnames[0]}" end $evm.log("info", "SCAP - Server: #{theserver}") #USER = 'cf3operator' USER = $evm.object['vm_user'] PASS = $evm.object.decrypt('vm_password') #Get the IP address of the client vm.ipaddresses.each do |vm_ipaddress| $evm.log("info", "SCAP - IP address: #{vm_ipaddress}") HOSTIP = vm_ipaddress end $evm.log("info", "Before logging into satellite...") #Get the xccdf file that the chosen profile is in Net::SSH.start( HOSTIP, USER, :password => PASS, :paranoid=> false ) do|ssh| PATH2CONTENT = ssh.exec!('for x in `locate xccdf|grep xml`; do grep -li "Profile id=\"' + "#{profile.strip}" + '" $x; done|head -1') end $evm.log("info", "SCAP - Directory: #{PATH2CONTENT}") $evm.log("info", "SCAP Before logging into satellite...") #Log into the Satellite @client = XMLRPC::Client.new2(@SATELLITE_URL) @key = @client.call('auth.login', @SATELLITE_LOGIN, @SATELLITE_PASSWORD) $evm.log("info", "SCAP After logging into satellite...") #Get the Satellite details of the client systeminfo = @client.call('system.getId', @key, theserver) $evm.log("info", "SCAP Satellite Details of Client: #{systeminfo}") #Check to see if the system is defined in Satellite if systeminfo[0] == nil $evm.log("info", "SCAP - #{theserver} doesn't exist in Satellite") exit MIQ_ABORT end @serverID = systeminfo[0]["id"] systemname = systeminfo[0]['name'] $evm.log("info", "Scheduling SCAP for #{systemname}") #Get set of scans before we start existingresults= @client.call('system.scap.listXccdfScans', @key, @serverID) $evm.log("info", "SCAP ExistingResults #{existingresults}") latestIDbeforestart=latestsatelliteresultID(existingresults,profile) $evm.log("info", "SCAP LatestSatelliteResultID #{latestIDbeforestart}") #Schedule a SCAP scan scanID = @client.call('system.scap.scheduleXccdfScan', @key, @serverID, PATH2CONTENT, @PROFILE) $evm.log("info", "SCAPSched SCANS: #{scanID}") # #Force the client to check-in to run the scan $evm.log("info", "SCAP - Starting a rhn_check for #{theserver} #{HOSTIP}") Net::SSH.start( HOSTIP, USER, :password => PASS, :paranoid=> false ) do|ssh| rhn_check = ssh.exec!('/usr/sbin/rhn_check') end i=0 num=10 foundresults=false while i <num do sleep 10 $evm.log("info", "SCAPSched loop: #{i}") i +=1 theresults = @client.call('system.scap.listXccdfScans', @key, @serverID) $evm.log("info", "SCAPSched Results: #{theresults}") currentmaxID=latestsatelliteresultID(theresults,profile) $evm.log("info", "SCAP CurrentMaxID #{currentmaxID}") if currentmaxID != latestIDbeforestart $evm.log("info", "SCAP Results are done!: #{currentmaxID}") foundresults=true break end end if foundresults==false $evm.log("info","SCAP Unable to get results after timeout") exit MIQ_ERROR end failresult=false theresults = @client.call('system.scap.getXccdfScanRuleResults', @key, currentmaxID) for theresult in theresults do if theresult["result"] == "fail" failresult = true break end end #Tag the VM with the relevant compliance/non-compliance result #The catagory/tag will should be in the format: # scap_{profile}/compliant # scap_{profile}/non_compliant #Get the profile and massage it to work within the name convention theprofile = @client.call('system.scap.getXccdfScanDetails', @key, currentmaxID) #Added:6/9/16 endtime=theprofile["end_time"] #$evm.log("info","===HERE_IS_END_TIME====== #{endtime.to_time.httpdate}") #vm.custom_set("lastendscantime",endtime.to_time.httpdate) timestamp = endtime.to_time.to_s $evm.log("info","===HERE_IS_END_TIME====== #{timestamp}") vm.custom_set("lastendscantime",timestamp) #profiledown = theprofile["profile"].downcase #profile = profiledown.tr("-", "_") if failresult==true profilecategory = "scap_noncompliant" category_to_remove = "scap_compliant" else profilecategory= "scap_compliant" category_to_remove = "scap_noncompliant" end #To ensure that we have a self-managed environment, if the tags for the profile don't exist, create them #Start with the tag category if $evm.execute('category_exists?', "#{profilecategory}") $evm.log("info", "SCAPCheck - #{profilecategory} exists") else $evm.log("info", "SCAPCheck - Adding new category: #{profilecategory}") $evm.execute('category_create', :name => "#{profilecategory}", :single_value => false, :description => "#{profilecategory}") end #And then the tags if $evm.execute('tag_exists?', "#{profilecategory}", "#{profile}") $evm.log("info", "SCAPCheck - #{profile} exists and is evaluated") else $evm.log("info", "SCAPCheck - Adding new tags for #{profile}") $evm.execute('tag_create',"#{profilecategory}", :name => "#{profile}", :description => "#{profile}") end loggedincfuser = $evm.root['user'] $evm.log("info", "USERNAME: #{loggedincfuser.userid}") if failresult == true vm.tag_assign("#{profilecategory}/#{profile}") $evm.log("info", "You have an OpenSCAP Scan Failure! Your VM: #{theserver} has failed the following SCAP policy profile: #{profile}") to = "lkerner@redhat.com" from = "noreply@redhat.com" subject = "You have an OpenSCAP Scan Failure! Your VM: #{theserver} has failed the following SCAP policy profile: #{profile}" body = "Hi #{loggedincfuser.userid}, <br><br> You have an OpenSCAP Scan Failure! Your VM :<b>#{theserver}</b> has failed the following SCAP policy profile: <b>#{profile}</b>.<br>Please fix the security failures within 48 hours. Your VM will automatically be remediated if it fails the security scan checks in 48 hours.<br><br>Thank You for your cooperation.<br><br>From,<br>Your Friendly Security Team" $evm.execute('send_email', to, from , subject, body) #SERVICENOW subjectservicenow="#{theserver} failed SCAP policy: #{profile}.VM owner is :#{loggedincfuser.userid}." body_hash['short_description'] = subjectservicenow # call servicenow $evm.log(:info, "Calling ServiceNow: incident information: #{body_hash.inspect}") insert_incident_result = call_servicenow(:post, 'incident', body_hash) #$evm.log(:info, "insert_incident_result: #{insert_incident_result.inspect}") $evm.log(:info, "insert_incident_result: #{insert_incident_result.inspect}") $evm.log(:info, "number: #{insert_incident_result['number']}") $evm.log(:info, "sys_id: #{insert_incident_result['sys_id']}") $evm.log(:info, "Adding custom attribute :servicenow_incident_number => #{insert_incident_result['number']} to #{$evm.root['vmdb_object_type']}: #{object.name}") object.custom_set(:servicenow_incident_number, insert_incident_result['number'].to_s) $evm.log(:info, "Adding custom attribute :servicenow_incident_sysid => #{insert_incident_result['sys_id']}> to #{$evm.root['vmdb_object_type']}: #{object.name}") object.custom_set(:servicenow_incident_sysid, insert_incident_result['sys_id'].to_s) else vm.tag_assign("#{profilecategory}/#{profile}") $evm.log("info", "SCAPCheck - #{theserver} has passed all SCAP(#{profile}) policies") end vm.tag_unassign("#{category_to_remove}/#{profile}") @client.call('auth.logout', @key) $evm.log("info", "SCAPSched Method Ended") exit MIQ_OK
module TalksHelper def youtube_link?(url) url.include?("youtube.com") || url.include?("youtu.be") end def parse_url_for_embed(url) if url.include?("watch?v=") url["watch?v="] = "embed/" elsif url.include?("youtu.be/") url["youtu.be/"] = "youtube.com/embed/" end if url.include?("&") url[/&.*/] = "" end end def make_youtube_tag(url) parse_url_for_embed(url) iframe = content_tag( :iframe, '', # empty body width: 560, height: 315, src: "#{url}", frameborder: 0, allowfullscreen: true ) content_tag(:div, iframe, class: 'youtube-container') end end
# typed: true # frozen_string_literal: true require "ast/node" module Packwerk class ParsedConstantDefinitions def initialize(root_node:) @local_definitions = {} collect_local_definitions_from_root(root_node) if root_node end def local_reference?(constant_name, location: nil, namespace_path: []) qualifications = self.class.reference_qualifications(constant_name, namespace_path: namespace_path) qualifications.any? do |name| @local_definitions[name] && @local_definitions[name] != location end end # What fully qualified constants can this constant refer to in this context? def self.reference_qualifications(constant_name, namespace_path:) return [constant_name] if constant_name.start_with?("::") fully_qualified_constant_name = "::#{constant_name}" possible_namespaces = namespace_path.each_with_object([""]) do |current, acc| acc << "#{acc.last}::#{current}" if acc.last && current end possible_namespaces.map { |namespace| namespace + fully_qualified_constant_name } end private def collect_local_definitions_from_root(node, current_namespace_path = []) if Node.constant_assignment?(node) add_definition(Node.constant_name(node), current_namespace_path, Node.name_location(node)) elsif Node.module_name_from_definition(node) # handle compact constant nesting (e.g. "module Sales::Order") tempnode = node while (tempnode = Node.each_child(tempnode).find { |n| Node.constant?(n) }) add_definition(Node.constant_name(tempnode), current_namespace_path, Node.name_location(tempnode)) end current_namespace_path += Node.class_or_module_name(node).split("::") end Node.each_child(node) { |child| collect_local_definitions_from_root(child, current_namespace_path) } end def add_definition(constant_name, current_namespace_path, location) fully_qualified_constant = [""].concat(current_namespace_path).push(constant_name).join("::") @local_definitions[fully_qualified_constant] = location end end end
class AddClinicIdToTeamMembers < ActiveRecord::Migration[6.1] def change add_column :team_members, :clinic_id, :integer end end
require 'open-uri' require 'json' class Twitter def initialize base_url= "https://api.twitter.com/1/users/lookup.json?" end def getUser(username) query_url = base_url + "screen_name" + username result_json = open(query_url).read result = JSON.parse(result_json) return result end end
require 'spec_helper' describe "Clients" do before(:each) do @employee = Factory(:employee) visit signin_path fill_in :email, :with => @employee.email fill_in :password, :with => @employee.password click_button end describe "add client" do describe "failure" do it "should not add a new client" do lambda do visit addclient_path fill_in "First name", :with => "" fill_in "Last name", :with => "" fill_in "Email", :with => "" fill_in "Phone", :with => "" click_button response.should render_template('clients/new') response.should have_selector("div#error_explanation") end.should_not change(Client, :count) end end #End Registration Failure describe "success" do it "should add a new client" do lambda do visit addclient_path fill_in "First name", :with => "Example" fill_in "Last name", :with => "Client" fill_in "Email", :with => "client@example.com" fill_in "Phone", :with => "0123456789" click_button response.should have_selector("div.flash.success", :content => "Welcome") response.should render_template('clients/show') end.should change(Client, :count).by(1) end end #End Registration Success end #End Register end
Smartwaiter::Application.routes.draw do devise_for :users root 'welcome#index' get "waiter/index" get "/waiters/index" get '/bartenders/index' get '/homes/index' get '/chefs/index' get "/helper/index" get '/managers/index' get '/users/sign_up' => 'devise/sessions#new' get "helper/index" get "helper/clean_table/:id" => "helper#clean_table", :as => 'clean_tables' get "managers/index" get "bartenders/delivery/:id" => "bartenders#delivery", :as =>'drink_delivery' get "bartenders/index" get "chefs/delivery/:id" => "chefs#delivery", :as =>'delivery' get "chefs/index" get "waiters/index" get "waiters/take_order/:id" => "waiters#take_order", :as => 'take_order' get "waiters/take_drink_order/:id" => "waiters#take_drink_order", :as => 'take_drink_order' get "waiters/set_table/:id" => "waiters#set_table", :as => 'set_table' get "waiters/serving_food/:id" => "waiters#serving_food", :as => 'serving_food' post "waiters/create_order" resources :food_orders resources :tables resources :foods # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
require 'google_maps_service' class Trip < ApplicationRecord validates_presence_of :name has_many :routes, -> {order "routes.created_at"}, dependent: :destroy has_many :destinations, through: :routes belongs_to :user def directions(origin, destination) GoogleMapsService::Client.new(key: ENV["gmaps_key"]).directions( [origin.latitude, origin.longitude], [destination.latitude, destination.longitude], mode: 'driving', alternatives: false).first[:legs].first[:duration][:value] end def forecast(destination, time) forecast = Faraday.get "https://api.darksky.net/forecast/#{ENV["forecast_key"]}/#{destination.latitude},#{destination.longitude},#{time.to_time.to_i}?exclude=minutely,hourly,daily,alerts" JSON.parse(forecast.body)["currently"] end def timezone(destination) timezone = Faraday.get "https://maps.googleapis.com/maps/api/timezone/json?location=#{destination.latitude},#{destination.longitude}&timestamp=#{(Time.now).to_time.to_i}&key=#{ENV["gmaps_key"]}" timezone_hours[JSON.parse(timezone.body)["timeZoneName"]] end def timezone_hours {"Pacific Standard Time" => -3600, "Mountain Standard Time" => 0, "Central Standard Time" => 3600, "Eastern Standard Time" => 7200} end end
class RemoveIndexFromArticles < ActiveRecord::Migration def change remove_column :articles, :category_id, :integer remove_column :articles, :sub_category_id, :integer remove_column :articles, :bearing_id, :integer end end
module Idcbatch module Ad class Connection ATTRS = %w{ company employeeNumber sAMAccountName proxyAddresses givenName sn employeeType extensionAttribute9 } attr_accessor :person def initialize args @persons = {} @args = self.to_ldap_args(args) @hosts = @args[:hosts] self.connect end def to_ldap_args(args) ldap_args = {} ldap_args[:hosts] = [] if args[:hosts].class == Array and !args[:hosts].empty? ldap_args[:hosts] = args[:hosts] end if args[:host].class == String and !args[:host].empty? ldap_args[:hosts] << args[:host] end ldap_args[:base] = args[:base_dn] if args[:base_dn] ldap_args[:encryption] = :simple_tls if args[:ssl] ldap_args[:port] = args[:port] if args[:port] auth = {} auth[:username] = args[:bind_dn] if args[:bind_dn] auth[:password] = args[:password] if args[:password] if auth[:username] and auth[:password] auth[:method] = :simple ldap_args[:auth] = auth end ldap_args end def connect @connections = [] @hosts.each do |host| args = @args args[:host] = host conn = Net::LDAP.new(args) @connections << conn end @next_connection_index = 0 end def update!(dn, attribute_name, attribute_value) if attribute_value.nil? connection.delete_attribute(dn, attribute_name) else connection.replace_attribute(dn, attribute_name, attribute_value) end end def find_all_by_sam_account_name(sam_account_name) find_all_by_filter "(&(objectClass=user)(sAMAccountName=#{sam_account_name}))" end def account(username) return nil if username.nil? result = self.find_all_by_sam_account_name(username) if result.size == 1 return result[0] elsif result.size > 1 $LOG.debug("More than one result: #{result.size} results. Don't know what to with #{username}.") nil else return nil end end def cleanup @connections.each { |c| c.unbind } end private def find_all_by_filter(search_filter) results = [] connection.search(:base => @args[:base], :attributes => ATTRS, :filter => search_filter, :return_result => true) { |entry| results << Idcbatch::Ad::Person.new(self, entry) } results end def connection conn = @connections[@next_connection_index] if ((@connections.length - 1) == @next_connection_index) @next_connection_index = 0 else @next_connection_index += 1 end conn end end end end
class Time def remaining toDate return 'n/d' if toDate.blank? intervals = [["d", 1], ["h", 24], ["m", 60]] elapsed = toDate.to_datetime - self.to_datetime interval = 1.0 parts = intervals.collect do |name, new_interval| interval /= new_interval number, elapsed = elapsed.abs.divmod(interval) "#{number.to_i}#{name}" unless number.to_i == 0 end "#{parts.join}" end end
class Api::V1::FamiliesController < ApplicationController protect_from_forgery unless: -> { request.format.json? } before_action :authenticate_user! def index render json: User.find(current_user.id).families end def show family = Family.find(params[:id]) if family && Family.find(params[:id]).users.include?(current_user) render json: family else render json: "You are not authorized to view this group posts." end end def create end private def family_params params.permit(:name) end def authorize_user if !user_signed_in? raise ActionController::RoutingError.new("User is not signed in") end end end
require "rails_helper" RSpec.describe Reports::RegionsController, type: :controller do let(:jan_2020) { Time.parse("January 1 2020") } let(:dec_2019_period) { Period.month(Date.parse("December 2019")) } let(:organization) { FactoryBot.create(:organization) } let(:cvho) { create(:admin, :manager, :with_access, resource: organization, organization: organization) } let(:call_center_user) { create(:admin, :call_center, full_name: "call_center") } let(:facility_group_1) { FactoryBot.create(:facility_group, name: "facility_group_1", organization: organization) } let(:facility_1) { FactoryBot.create(:facility, name: "facility_1", facility_group: facility_group_1) } describe "show" do render_views before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, name: "CHC Barnagar", facility_group: @facility_group) @facility_region = @facility.region end it "redirects if matching region slug not found" do sign_in(cvho.email_authentication) get :show, params: {id: "String-unknown", report_scope: "bad-report_scope"} expect(flash[:alert]).to eq("You are not authorized to perform this action.") expect(response).to be_redirect end it "redirects if user does not have proper access to org" do district_official = create(:admin, :viewer_reports_only, :with_access, resource: @facility_group) sign_in(district_official.email_authentication) get :show, params: {id: @facility_group.organization.slug, report_scope: "organization"} expect(flash[:alert]).to eq("You are not authorized to perform this action.") expect(response).to be_redirect end it "redirects if user does not have authorization to region" do other_fg = create(:facility_group, name: "other facility group") other_fg.facilities << build(:facility, name: "other facility") user = create(:admin, :viewer_reports_only, :with_access, resource: other_fg) sign_in(user.email_authentication) get :show, params: {id: @facility_region.slug, report_scope: "facility"} expect(flash[:alert]).to eq("You are not authorized to perform this action.") expect(response).to be_redirect end it "finds a district region if it has different slug compared to the facility group" do other_fg = create(:facility_group, name: "other facility group", organization: organization) region = other_fg.region slug = region.slug region.update!(slug: "#{slug}-district") expect(region.slug).to_not eq(other_fg.slug) other_fg.facilities << build(:facility, name: "other facility") user = create(:admin, :viewer_reports_only, :with_access, resource: other_fg) sign_in(user.email_authentication) get :show, params: {id: region.slug, report_scope: "district"} expect(response).to be_successful end it "renders successfully for an organization" do other_fg = create(:facility_group, name: "other facility group", organization: organization) create(:facility, name: "other facility", facility_group: other_fg) user = create(:admin, :viewer_reports_only, :with_access, resource: other_fg) sign_in(user.email_authentication) get :show, params: {id: organization.slug, report_scope: "organization"} end it "renders successfully if report viewer has access to region" do other_fg = create(:facility_group, name: "other facility group", organization: organization) create(:facility, name: "other facility", facility_group: other_fg) user = create(:admin, :viewer_reports_only, :with_access, resource: other_fg) sign_in(user.email_authentication) get :show, params: {id: other_fg.region.slug, report_scope: "district"} expect(response).to be_successful end it "returns period info for every month" do Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :show, params: {id: @facility.facility_group.region.slug, report_scope: "district"} end data = assigns(:data) period_hash = { name: "Dec-2019", bp_control_start_date: "1-Oct-2019", bp_control_end_date: "31-Dec-2019", ltfu_since_date: "31-Dec-2018", bp_control_registration_date: "30-Sep-2019" } expect(data[:period_info][dec_2019_period]).to eq(period_hash) end it "returns period info for current month" do today = Date.current Timecop.freeze(today) do patient = create(:patient, registration_facility: @facility, recorded_at: 2.months.ago) create(:bp_with_encounter, :under_control, recorded_at: Time.current.yesterday, patient: patient, facility: @facility) refresh_views sign_in(cvho.email_authentication) get :show, params: {id: @facility.facility_group.slug, report_scope: "district"} end data = assigns(:data) expect(data[:period_info][Period.month(today.beginning_of_month)]).to_not be_nil end it "retrieves district data" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -4)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :show, params: {id: @facility.facility_group.slug, report_scope: "district"} end expect(response).to be_successful data = assigns(:data) expect(data[:controlled_patients].size).to eq(10) # sanity check expect(data[:controlled_patients][dec_2019_period]).to eq(1) end it "retrieves facility data" do Time.parse("January 1 2020") patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -4)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :show, params: {id: @facility_region.slug, report_scope: "facility"} end expect(response).to be_successful data = assigns(:data) expect(data[:controlled_patients].size).to eq(10) # sanity check expect(data[:controlled_patients][Date.parse("Dec 2019").to_period]).to eq(1) end it "retrieves block data" do patient_2 = create(:patient, registration_facility: @facility, recorded_at: "June 01 2019 00:00:00 UTC", registration_user: cvho) create(:bp_with_encounter, :hypertensive, recorded_at: "Feb 2020", facility: @facility, patient: patient_2, user: cvho) patient_1 = create(:patient, registration_facility: @facility, recorded_at: "September 01 2019 00:00:00 UTC", registration_user: cvho) create(:bp_with_encounter, :under_control, recorded_at: "December 10th 2019", patient: patient_1, facility: @facility, user: cvho) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility, user: cvho) refresh_views block = @facility.region.block_region Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :show, params: {id: block.to_param, report_scope: "block"} end expect(response).to be_successful data = assigns(:data) expect(data[:registrations][Period.month("June 2019")]).to eq(1) expect(data[:registrations][Period.month("September 2019")]).to eq(1) expect(data[:controlled_patients][Period.month("Dec 2019")]).to eq(1) expect(data[:uncontrolled_patients][Period.month("Feb 2020")]).to eq(1) expect(data[:uncontrolled_patients_rate][Period.month("Feb 2020")]).to eq(50) expect(data[:missed_visits][Period.month("September 2019")]).to eq(1) expect(data[:missed_visits][Period.month("May 2020")]).to eq(2) end it "works when a user requests data just before the earliest registration date" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -4)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views one_month_before = patient.recorded_at.advance(months: -1) sign_in(cvho.email_authentication) get :show, params: {id: @facility_region.slug, report_scope: "facility", period: {type: :month, value: one_month_before}} expect(response).to be_successful data = assigns(:data) expect(data[:controlled_patients]).to eq({}) expect(data[:period_info]).to eq({}) end it "works for very old dates" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -4)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) refresh_views ten_years_ago = patient.recorded_at.advance(years: -10) sign_in(cvho.email_authentication) get :show, params: {id: @facility_region.slug, report_scope: "facility", period: {type: :month, value: ten_years_ago}} expect(response).to be_successful data = assigns(:data) expect(data[:controlled_patients]).to eq({}) expect(data[:period_info]).to eq({}) end it "works for far future dates" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -4)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) refresh_views ten_years_from_now = patient.recorded_at.advance(years: -10) sign_in(cvho.email_authentication) get :show, params: {id: @facility_region.slug, report_scope: "facility", period: {type: :month, value: ten_years_from_now}} expect(response).to be_successful data = assigns(:data) expect(data[:controlled_patients]).to eq({}) expect(data[:period_info]).to eq({}) end context "when region has diabetes management enabled" do it "contains a link to the diabetes management reports" do @facility.update(enable_diabetes_management: true) sign_in(cvho.email_authentication) get :show, params: {id: @facility_region.slug, report_scope: "facility"} assert_select "a[href*='diabetes']", count: 1 end end end describe "index" do render_views before do @facility_group = create(:facility_group, organization: organization) @facility_1 = create(:facility, name: "Facility 1", block: "Block 1", facility_group: @facility_group) @facility_2 = create(:facility, name: "Facility 2", block: "Block 1", facility_group: @facility_group) @block = @facility_1.block_region end it "loads nothing if user has no access to any regions" do sign_in(call_center_user.email_authentication) get :index expect(assigns[:accessible_regions]).to eq({}) expect(response).to be_successful end it "only loads districts the user has access to" do sign_in(cvho.email_authentication) get :index expect(response).to be_successful facility_regions = [@facility_1.region, @facility_2.region] org_region = organization.region state_region = @facility_1.region.state_region expect(assigns[:accessible_regions].keys).to eq([org_region]) expect(assigns[:accessible_regions][org_region].keys).to match_array(org_region.state_regions) expect(assigns[:accessible_regions].dig(org_region, state_region, @facility_group.region, @block.region)).to match_array(facility_regions) end end describe "details" do render_views before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, name: "CHC Barnagar", facility_group: @facility_group) end it "is successful for an organization" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -1)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views org = @facility_group.organization Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :details, params: {id: org.slug, report_scope: "organization"} end expect(response).to be_successful end it "is successful for a district" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -1)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :details, params: {id: @facility.facility_group.region.slug, report_scope: "district"} end expect(response).to be_successful end it "is successful for a block" do patient_2 = create(:patient, registration_facility: @facility, recorded_at: "June 01 2019 00:00:00 UTC", registration_user: cvho) create(:bp_with_encounter, :hypertensive, recorded_at: "Feb 2020", facility: @facility, patient: patient_2, user: cvho) patient_1 = create(:patient, registration_facility: @facility, recorded_at: "September 01 2019 00:00:00 UTC", registration_user: cvho) create(:bp_with_encounter, :under_control, recorded_at: "December 10th 2019", patient: patient_1, facility: @facility, user: cvho) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility, user: cvho) refresh_views block = @facility.region.block_region Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :details, params: {id: block.slug, report_scope: "block"} end expect(response).to be_successful end it "is successful for a facility" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -1)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :details, params: {id: @facility.region.slug, report_scope: "facility"} end expect(response).to be_successful end it "renders period hash info" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -1)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :details, params: {id: @facility.region.slug, report_scope: "facility"} period_info = assigns(:details_chart_data)[:ltfu_trend][:period_info] expect(period_info.keys.size).to eq(18) period_info.each do |period, hsh| expect(hsh).to eq(period.to_hash) end end end end describe "cohort" do render_views before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, name: "CHC Barnagar", facility_group: @facility_group) end it "retrieves monthly cohort data by default" do patient = create(:patient, registration_facility: @facility, registration_user: cvho, recorded_at: jan_2020.advance(months: -1)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :cohort, params: {id: @facility.facility_group.slug, report_scope: "district"} end expect(response).to be_successful data = assigns(:cohort_data) dec_cohort = data.find { |hsh| hsh["registration_period"] == "Dec-2019" } expect(dec_cohort["registered"]).to eq(1) end it "can retrieve quarterly cohort data" do patient = create(:patient, registration_facility: @facility, registration_user: cvho, recorded_at: jan_2020.advance(months: -2)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020 + 1.day, patient: patient, facility: @facility) refresh_views Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :cohort, params: {id: @facility.facility_group.slug, report_scope: "district", period: {type: "quarter", value: "Q2-2020"}} expect(response).to be_successful data = assigns(:cohort_data) expect(data.size).to eq(6) q2_data = data[1] expect(q2_data["results_in"]).to eq("Q1-2020") expect(q2_data["registered"]).to eq(1) expect(q2_data["controlled"]).to eq(1) end end it "can retrieve quarterly cohort data for a new facility with no data" do refresh_views Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) get :cohort, params: {id: @facility.facility_group.slug, report_scope: "district", period: {type: "quarter", value: "Q2-2020"}} expect(response).to be_successful data = assigns(:cohort_data) expect(data.size).to eq(6) q2_data = data[1] expect(q2_data["results_in"]).to eq("Q1-2020") expect(q2_data["period"]).to eq(Period.quarter("Q1-2020")) expect(q2_data["registered"]).to be_nil expect(q2_data["controlled"]).to be_nil end end end describe "download" do render_views before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, name: "CHC Barnagar", facility_group: @facility_group) end it "retrieves cohort data for a facility" do patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -1)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views result = nil Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) result = get :download, params: {id: @facility.slug, report_scope: "facility", period: "month", format: "csv"} end expect(response).to be_successful expect(response.body).to include("CHC Barnagar Monthly Cohort Report") expect(response.headers["Content-Disposition"]).to include('filename="facility-monthly-cohort-report_CHC-Barnagar') expect(result).to render_template("cohort") end it "retrieves cohort data for a facility group" do facility_group = @facility.facility_group patient = create(:patient, registration_facility: @facility, recorded_at: jan_2020.advance(months: -1)) create(:bp_with_encounter, :under_control, recorded_at: jan_2020.advance(months: -1), patient: patient, facility: @facility) create(:bp_with_encounter, :hypertensive, recorded_at: jan_2020, facility: @facility) refresh_views result = nil Timecop.freeze("June 1 2020") do sign_in(cvho.email_authentication) result = get :download, params: {id: facility_group.slug, report_scope: "district", period: "quarter", format: "csv"} end expect(response).to be_successful expect(response.body).to include("#{facility_group.name} Quarterly Cohort Report") expect(response.headers["Content-Disposition"]).to include('filename="district-quarterly-cohort-report_') expect(result).to render_template("facility_group_cohort") end end describe "monthly_district_report" do before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, facility_group: @facility_group) sign_in(cvho.email_authentication) end it "retrieves the hypertension monthly district report" do Flipper.enable(:monthly_district_report) district = @facility_group.region refresh_views files = [] Timecop.freeze("June 1 2020") do get :hypertension_monthly_district_report, params: {id: district.slug, report_scope: "district", format: "zip"} end expect(response).to be_successful Zip::File.open_buffer(response.body) do |zip| zip.map do |entry| files << entry.name end end expect(files).to match_array(%w[facility_data.csv block_data.csv district_data.csv]) expect(response.headers["Content-Disposition"]).to include("filename=\"monthly-district-hypertension-report-#{district.slug}-jun-2020.zip\"") end it "retrieves the diabetes monthly district report" do Flipper.enable(:monthly_district_report) district = @facility_group.region refresh_views files = [] Timecop.freeze("June 1 2020") do get :diabetes_monthly_district_report, params: {id: district.slug, report_scope: "district", format: "zip"} end expect(response).to be_successful Zip::File.open_buffer(response.body) do |zip| zip.map do |entry| files << entry.name end end expect(files).to match_array(%w[facility_data.csv block_data.csv district_data.csv]) expect(response.headers["Content-Disposition"]).to include("filename=\"monthly-district-diabetes-report-#{district.slug}-jun-2020.zip\"") end end describe "#whatsapp_graphics" do render_views before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, name: "CHC Barnagar", facility_group: @facility_group) sign_in(cvho.email_authentication) end describe "html requested" do it "renders graphics_header partial" do get :whatsapp_graphics, format: :html, params: {id: @facility.region.slug, report_scope: "facility"} expect(response).to be_ok expect(response).to render_template("shared/graphics/_graphics_partial") end end describe "png requested" do it "renders the image template for downloading" do get :whatsapp_graphics, format: :png, params: {id: @facility_group.region.slug, report_scope: "district"} expect(response).to be_ok expect(response).to render_template("shared/graphics/image_template") end end end describe "#hypertension_monthly_district_data" do before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, facility_group: @facility_group) @region = @facility.region.district_region sign_in(cvho.email_authentication) end it "returns 401 when user is not authorized" do sign_out(cvho.email_authentication) get :hypertension_monthly_district_data, params: {id: @region.slug, report_scope: "district", format: "csv"} expect(response.status).to eq(401) end it "returns 302 found with invalid region" do get :hypertension_monthly_district_data, params: {id: "not-found", report_scope: "district", format: "csv"} expect(response.status).to eq(302) end it "returns 302 if region is not district" do get :hypertension_monthly_district_data, params: {id: @facility.slug, report_scope: "district", format: "csv"} expect(response.status).to eq(302) end it "calls csv service and returns 200 with csv data" do Timecop.freeze("June 15th 2020") do expect_any_instance_of(MonthlyDistrictData::HypertensionDataExporter).to receive(:report).and_call_original get :hypertension_monthly_district_data, params: {id: @region.slug, report_scope: "district", format: "csv"} expect(response.status).to eq(200) expect(response.body).to include("Monthly facility data for #{@region.name} #{Date.current.strftime("%B %Y")}") report_date = Date.current.strftime("%b-%Y").downcase expected_filename = "monthly-facility-hypertension-data-#{@region.slug}-#{report_date}.csv" expect(response.headers["Content-Disposition"]).to include(%(filename="#{expected_filename}")) end end it "passes the provided period to the csv service" do period = Period.month("July 2018") expect(MonthlyDistrictData::HypertensionDataExporter).to receive(:new).with(region: @region, period: period, medications_dispensation_enabled: false) .and_call_original get :hypertension_monthly_district_data, params: {id: @region.slug, report_scope: "district", format: "csv", period: period.attributes} end end describe "#diabetes_monthly_district_data" do before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, facility_group: @facility_group) @region = @facility.region.district_region sign_in(cvho.email_authentication) end it "returns 401 when user is not authorized" do sign_out(cvho.email_authentication) get :diabetes_monthly_district_data, params: {id: @region.slug, report_scope: "district", format: "csv"} expect(response.status).to eq(401) end it "returns 302 found with invalid region" do get :diabetes_monthly_district_data, params: {id: "not-found", report_scope: "district", format: "csv"} expect(response.status).to eq(302) end it "returns 302 if region is not district" do get :diabetes_monthly_district_data, params: {id: @facility.slug, report_scope: "district", format: "csv"} expect(response.status).to eq(302) end it "calls csv service and returns 200 with csv data" do Timecop.freeze("June 15th 2020") do expect_any_instance_of(MonthlyDistrictData::DiabetesDataExporter).to receive(:report).and_call_original get :diabetes_monthly_district_data, params: {id: @region.slug, report_scope: "district", format: "csv"} expect(response.status).to eq(200) expect(response.body).to include("Monthly facility data for #{@region.name} #{Date.current.strftime("%B %Y")}") report_date = Date.current.strftime("%b-%Y").downcase expected_filename = "monthly-facility-diabetes-data-#{@region.slug}-#{report_date}.csv" expect(response.headers["Content-Disposition"]).to include(%(filename="#{expected_filename}")) end end it "passes the provided period to the csv service" do period = Period.month("July 2018") expect(MonthlyDistrictData::DiabetesDataExporter).to receive(:new).with(region: @region, period: period, medications_dispensation_enabled: false) .and_call_original get :diabetes_monthly_district_data, params: {id: @region.slug, report_scope: "district", format: "csv", period: period.attributes} end end describe "#hypertension_monthly_state_data" do before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, facility_group: @facility_group) @region = @facility.region.state_region sign_in(cvho.email_authentication) end it "returns 401 when user is not authorized" do sign_out(cvho.email_authentication) get :hypertension_monthly_state_data, params: {id: @region.slug, report_scope: "state", format: "csv"} expect(response.status).to eq(401) end it "returns 302 found with invalid region" do get :hypertension_monthly_state_data, params: {id: "not-found", report_scope: "state", format: "csv"} expect(response.status).to eq(302) end it "returns 302 if region is not state" do get :hypertension_monthly_state_data, params: {id: @facility.slug, report_scope: "state", format: "csv"} expect(response.status).to eq(302) end it "calls csv service and returns 200 with csv data" do Timecop.freeze("June 15th 2020") do expect_any_instance_of(MonthlyStateData::Exporter).to receive(:report).and_call_original get :hypertension_monthly_state_data, params: {id: @region.slug, report_scope: "state", format: "csv"} expect(response.status).to eq(200) expect(response.body).to include("Monthly district data for #{@region.name} #{Date.current.strftime("%B %Y")}") report_date = Date.current.strftime("%b-%Y").downcase expected_filename = "monthly-district-hypertension-data-#{@region.slug}-#{report_date}.csv" expect(response.headers["Content-Disposition"]).to include(%(filename="#{expected_filename}")) end end it "passes the provided period to the csv service" do period = Period.month("July 2018") expect(MonthlyStateData::HypertensionDataExporter).to receive(:new).with(region: @region, period: period, medications_dispensation_enabled: false) .and_call_original get :hypertension_monthly_state_data, params: {id: @region.slug, report_scope: "state", format: "csv", period: period.attributes} end end describe "#diabetes_monthly_state_data" do before do @facility_group = create(:facility_group, organization: organization) @facility = create(:facility, facility_group: @facility_group) @region = @facility.region.state_region sign_in(cvho.email_authentication) end it "returns 401 when user is not authorized" do sign_out(cvho.email_authentication) get :diabetes_monthly_state_data, params: {id: @region.slug, report_scope: "state", format: "csv"} expect(response.status).to eq(401) end it "returns 302 found with invalid region" do get :diabetes_monthly_state_data, params: {id: "not-found", report_scope: "state", format: "csv"} expect(response.status).to eq(302) end it "returns 302 if region is not state" do get :diabetes_monthly_state_data, params: {id: @facility.slug, report_scope: "state", format: "csv"} expect(response.status).to eq(302) end it "calls csv service and returns 200 with csv data" do Timecop.freeze("June 15th 2020") do expect_any_instance_of(MonthlyStateData::Exporter).to receive(:report).and_call_original get :diabetes_monthly_state_data, params: {id: @region.slug, report_scope: "state", format: "csv"} expect(response.status).to eq(200) expect(response.body).to include("Monthly district data for #{@region.name} #{Date.current.strftime("%B %Y")}") report_date = Date.current.strftime("%b-%Y").downcase expected_filename = "monthly-district-diabetes-data-#{@region.slug}-#{report_date}.csv" expect(response.headers["Content-Disposition"]).to include(%(filename="#{expected_filename}")) end end it "passes the provided period to the csv service" do period = Period.month("July 2018") expect(MonthlyStateData::DiabetesDataExporter).to receive(:new).with(region: @region, period: period, medications_dispensation_enabled: false) .and_call_original get :diabetes_monthly_state_data, params: {id: @region.slug, report_scope: "state", format: "csv", period: period.attributes} end end describe "#diabetes" do let(:facility) { create(:facility, facility_group: facility_group_1, enable_diabetes_management: true) } let(:facility_region) { create(:region, region_type: :facility, source: facility, reparent_to: Region.root) } before do sign_in(cvho.email_authentication) end it "return diabetes reports page" do get :diabetes, params: {id: facility_region.slug, report_scope: "facility"} expect(response).to have_http_status(:ok) end end end
require 'ostruct' # ModifiableStruct is a variation on OpenStruct where and variable get for an # unset variable will result in a NoMethodError. This allows you to safely add # and get variables without having to track down nils introduced by bad method # calls. class ModifiableStruct < OpenStruct def method_missing(method, *args) raise key_error(method) unless method.to_s.end_with?('=') super end def key_error(name) NoMethodError.new "no #{name} key set yet" end end
# O módulo LogsController cuida do histírico das movimentações de valores class LogsController < ApplicationController before_action :set_log, only: [:show, :edit, :update, :destroy] before_action {not_admin(root_path)} before_action only: [:index] do redirect_to(budgets_path) end def initialize super @log = nil end # GET /logs def index @logs = Log.all end # GET /logs/1 def show end # GET /logs/new def new @log = Log.new end # GET /logs/1/edit def edit end # POST /logs # :reek:DuplicateMethodCall def create @log = Log.new(log_params) @log.budget = Budget.first retorno = add_value(@log.value) if retorno[0] create_confirm(@log, 'Movimentação criada com sucesso.', budgets_path) else format.html { redirect_to budgets_path , notice: retorno[1] } end end # PATCH/PUT /logs/1 # :reek:DuplicateMethodCall def update respond_to do |format| old_value = @log.value if @log.update(log_params) add_value(@log.value - old_value) format.html { redirect_to @log, notice: 'Movimentação atualizada com sucesso.' } else format.html { render :edit } end end end # DELETE /logs/1 # :reek:DuplicateMethodCall def destroy @log.destroy respond_to do |format| format.html { redirect_to budgets_url, notice: 'Movimentação deletada com sucesso.' } end end private # Use callbacks to share common setup or constraints between actions. def set_log @log = Log.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def log_params params.require(:log).permit(:value, :description) end end
# == Schema Information # # Table name: notes # # id :integer not null, primary key # title :string(255) # content :text # user_id :integer # category_id :integer # created_at :datetime # updated_at :datetime # class Note < ActiveRecord::Base belongs_to :user belongs_to :category has_many :comments validates :title, :content, :category_id, :created_at, presence: true default_scope -> { order(created_at: :desc) } end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'snapshotar/version' Gem::Specification.new do |spec| spec.name = "snapshotar" spec.version = Snapshotar::VERSION spec.authors = ["Benjamin Müller"] spec.email = ["benjamin@berlab.io"] spec.description = %q{Make a snapshot of your rails database.} spec.summary = %q{In contrast to a database backup, snapshotAR is able to manage image references made with paperclip or carrierwave correctly. You are able to save your entire application or only parts of it and e.g. seed your test environments. } spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib","tasks"] spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "dotenv" spec.add_development_dependency 'mongoid', '~> 4.0.0' spec.add_development_dependency 'carrierwave-mongoid' spec.add_dependency 'aws-sdk', '~> 1.0' spec.add_dependency 'jbuilder' end
class EmailList # this version works with Brian Getting's Hominid gem: # script/plugin install git://github.com/bgetting/hominid.git cattr_accessor :errors private @@hominid = nil @@list = nil @@listid = nil def self.hominid ; @@hominid ; end def self.segment_id_from_name(name) self.init_hominid || return hominid.static_segments(@@listid).detect { |s| s['name'] == name }['id'] end public def self.disabled? Figaro.env.email_integration != 'MailChimp' end def self.enabled? ; !self.disabled? ; end def self.init_hominid Rails.logger.info("NOT initializing mailchimp") and return nil if self.disabled? return true if hominid apikey = Figaro.env.mailchimp_key @@list = Option.mailchimp_default_list_name if (apikey.blank? || @@list.blank?) Rails.logger.warn("NOT using Mailchimp, one or more necessary options are blank") return nil end begin @@hominid = Hominid::Base.new :api_key => apikey @@listid = hominid.find_list_id_by_name(@@list) rescue NoMethodError => e # dereference nil.[] means list not found Rails.logger.warn "Init Mailchimp: list '#{@@list}' not found" return nil rescue StandardError => e Rails.logger.info "Init Mailchimp failed: <#{e.message}>" return nil end Rails.logger.info "Init Mailchimp with default list '#{@@list}'" return true end def self.subscribe(cust, email=cust.email) self.init_hominid || return Rails.logger.info "Subscribe #{cust.full_name} as #{email}" msg = "Subscribing #{cust.full_name} <#{email}> to '#{@@list}'" begin hominid.subscribe( @@listid, email, {:FNAME => cust.first_name, :LNAME => cust.last_name}, {:email_type => 'html'}) Rails.logger.info msg rescue Exception => e Rails.logger.info [msg,e.message].join(': ') end end def self.update(cust, old_email) self.init_hominid || return Rails.logger.info "Update email for #{cust.full_name} from #{old_email} to #{cust.email}" begin # update existing entry msg = "Changing <#{old_email}> to <#{cust.email}> " << "for #{cust.full_name} in '#{@@list}'" hominid.update_member( @@listid, old_email, {:FNAME => cust.first_name, :LNAME => cust.last_name, :email => cust.email }) rescue Hominid::ListError => e if (e.message !~ /no record of/i) msg = "Hominid error: #{e.message}" else begin # was not on list previously msg = "Adding #{cust.email} to list #{@@list}" hominid.subscribe(@@listid, cust.email, {:FNAME => cust.first_name, :LNAME => cust.last_name}, {:email_type => 'html'}) rescue Exception => e throw e end end # here if all went well... Rails.logger.info msg rescue Exception => e Rails.logger.info [msg,e.message].join(': ') end end def self.unsubscribe(cust, email=cust.email) self.init_hominid || return Rails.logger.info "Unsubscribe #{cust.full_name} as #{email}" msg = "Unsubscribing #{cust.full_name} <#{email}> from '#{@@list}'" begin hominid.unsubscribe(@@listid, email) Rails.logger.info msg rescue Exception => e Rails.logger.info [msg,e.message].join(': ') end end def self.create_sublist_with_customers(name, customers) self.create_sublist(name) && self.add_to_sublist(name, customers) end def self.create_sublist(name) self.init_hominid || return begin hominid.add_static_segment(@@listid, name) return true rescue Exception => e error = "List segment '#{name}' could not be created: #{e.message}" Rails.logger.warn error self.errors = error return nil end end def self.get_sublists # returns array of 2-element arrays, each of which is [name,count] for static segments self.init_hominid || (return([])) begin segs = hominid.static_segments(@@listid).map { |seg| [seg['name'], seg['member_count']] } puts "Returning static segments: #{segs}" segs rescue Exception => e Rails.logger.info "Getting sublists: #{e.message}" [] end end def self.add_to_sublist(sublist,customers=[]) self.init_hominid || return begin seg_id = segment_id_from_name(sublist) emails = customers.select { |c| c.valid_email_address? }.map { |c| c.email } if emails.empty? self.errors = "None of the matching customers had valid email addresses." return 0 end result = hominid.static_segment_add_members(@@listid, seg_id, emails) if !result['errors'].blank? self.errors = "MailChimp was unable to add #{result['errors'].length} of the customers, usually because they aren't subscribed to the master list." end return result['success'].to_i rescue Exception => e self.errors = e.message Rails.logger.info "Adding #{customers.length} customers to sublist '#{sublist}': #{e.message}" return 0 end end end
module SitescanCommon # Product page scanning errors. # # type_id: 1 - page error, 2 - name error, 3 - price error, 4 - arhived. class SearchProductError < ActiveRecord::Base self.table_name = :search_product_errors belongs_to :search_result validates :type_id, uniqueness: { scope: :search_result_id } after_commit :search_product_reindex private def search_product_reindex search_result.search_product.reindex if search_result.search_product end end end
class ForumsController < ApplicationController controls_access_with do ForumSentinel.new :current_user => current_user, :forum => @forum end grants_access_to lambda { stubbed_method }, :denies_with => :redirect_to_index grants_access_to :denies_with => :sentinel_unauthorized do stubbed_method_two end grants_access_to :reorderable?, :only => [:reorder] grants_access_to :creatable?, :only => [:new, :create], :denies_with => :redirect_to_index grants_access_to :viewable?, :only => [:show], :denies_with => :sentinel_unauthorized grants_access_to :destroyable?, :only => [:destroy] on_denied_with :redirect_to_index do redirect_to url_for(:controller => "forums", :action => "secondary_index") end on_denied_with :sentinel_unauthorized do respond_to do |wants| wants.html do render :text => "This is an even more unique default restricted warning", :status => :forbidden end wants.any { head :forbidden } end end def index handle_successfully end def secondary_index handle_successfully end def new handle_successfully end def show handle_successfully end def edit handle_successfully end def update handle_successfully end def delete handle_successfully end private def handle_successfully render :text => "forums" end def stubbed_method true end def stubbed_method_two true end end
class UsersController < ApplicationController def index @user = current_user end def show @user = User.find_by_username(params[:id]) end def follow @user = User.find(params[:id]) if current_user if current_user == @user flash[:notice] = "You cannot follow yourself." redirect_back(fallback_location: root_path) else current_user.follow(@user) #RecommenderMailer.new_follower(@user).deliver if @user.notify_new_follower flash[:notice] = "You are now following the user." end else flash[:error] = "You must <a href='/users/sign_in'>login</a> to follow #{@user.monniker}.".html_safe end redirect_back(fallback_location: root_path) end def unfollow @user = User.find(params[:id]) if current_user current_user.stop_following(@user) flash[:notice] = "You are no longer following #{@user.email}." else flash[:error] = "You must <a href='/users/sign_in'>login</a> to unfollow #{@user.email}.".html_safe end redirect_back(fallback_location: root_path) end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB 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. module Mongo module Event # Adds convenience methods for adding listeners to event publishers. # # @since 2.0.0 module Subscriber # @return [ Event::Listeners ] event_listeners The listeners. attr_reader :event_listeners # Subscribe to the provided event. # # @example Subscribe to the event. # subscriber.subscribe_to('test', listener) # # @param [ String ] event The event. # @param [ Object ] listener The event listener. # # @since 2.0.0 def subscribe_to(event, listener) event_listeners.add_listener(event, listener) end end end end
class CreateMemberships < ActiveRecord::Migration def change create_table :memberships do |t| t.string :category, null: false t.integer :year, null: false t.decimal :price_paid, null: false t.date :date_paid, null: false t.boolean :active, default: true, null: false t.text :notes end end end
require 'rails_helper' RSpec.describe User, type: :model do describe 'Validations' do it 'should have first_name, last_name, email, password, password_confirmation to be valid' do user = User.create! first_name: 'yves', last_name: 'lastname', email: 'example@email.com', password: 'password', password_confirmation: 'password' expect(user).to be_valid end it 'should not be valid without a first name' do user = User.new first_name: nil, last_name: 'last', email: 'example@email.com', password: 'password', password_confirmation: 'password' expect(user).to_not be_valid expect(user.errors.full_messages).to include("First name can\'t be blank") end it 'should not be valid without a last name' do user = User.new first_name: 'yves', last_name: nil, email: 'example@email.com', password: 'password', password_confirmation: 'password' expect(user).to_not be_valid expect(user.errors.full_messages).to include('Last name can\'t be blank') end it 'should not be valid without an email' do user = User.new first_name: 'yves', last_name: 'lastname', email: nil, password: 'password', password_confirmation: 'password' expect(user).to_not be_valid expect(user.errors.full_messages).to include('Email can\'t be blank') end it 'should not be valid without password' do user = User.new first_name: 'yves', last_name: 'lastname', email: 'example@email.com', password: nil, password_confirmation: 'nil' expect(user).to_not be_valid expect(user.errors.full_messages).to include('Password can\'t be blank') end it 'should not be valid without matching password and confirmation' do user = User.new first_name: 'yves', last_name: 'lastname', email: 'example@email.com', password: 'password', password_confirmation: 'hotdogs' expect(user).to_not be_valid expect(user.errors.full_messages).to include('Password confirmation doesn\'t match Password') end it 'should not be valid with password shorter than 8 characters' do user = User.new first_name: 'yves', last_name: 'lastname', email: 'example@email.com', password: 'short', password_confirmation: 'short' expect(user).to_not be_valid expect(user.errors.full_messages).to include('Password is too short (minimum is 8 characters)') end it 'emails should be unique' do user1 = User.create first_name: 'yves', last_name: 'lastname', email: 'uppercase@email.com', password: 'password', password_confirmation: 'password' user2 = User.new first_name: 'bob', last_name: 'lastname', email: 'UPPERCASE@email.com', password: 'password', password_confirmation: 'password' expect(user1).to be_valid expect(user2).to_not be_valid end end describe '.authenticate_with_credentials' do it 'should' do user = User.create! first_name: 'yves', last_name: 'lastname', email: 'example@email.com', password: 'password', password_confirmation: 'password' user_auth = User.authenticate_with_credentials('example@email.com', 'password') expect(user_auth).to be_valid end it 'should be nil with wrong password' do user = User.create! first_name: 'yves', last_name: 'lastname', email: 'email@email.com', password: 'password', password_confirmation: 'password' user_auth = User.authenticate_with_credentials('email@email.com', 'password2') expect(user_auth).to be_nil end it 'should be nil with email that doesn\'t exist' do user = User.create! first_name: 'yves', last_name: 'lastname', email: 'example@email.com', password: 'password', password_confirmation: 'password' user_auth = User.authenticate_with_credentials('invalidemail@email.com', 'password') expect(user_auth).to be_nil end it 'should be valid with email with __ __ spaces before and after' do user = User.create! first_name: 'yves', last_name: 'lastname', email: 'email@email.com', password: 'password', password_confirmation: 'password' user_auth = User.authenticate_with_credentials(' email@email.com ', 'password') expect(user_auth).to be_valid end it 'should be valid with emails with dif case' do user = User.create! first_name: 'yves', last_name: 'lastname', email: 'uppercase@email.com', password: 'password', password_confirmation: 'password' user_auth = User.authenticate_with_credentials('UPPERCASE@email.CoM', 'password') expect(user_auth).to be_valid end end end
module DataMapper::Mongo::Spec module ResetHelper def reset_db DataMapper.repository.adapter.send(:database).collections.each do |collection| next if collection.name =~ /^system/ collection.drop end end end end
require File.dirname(__FILE__) + '/../spec_helper' require 'string_utils' include ApplicationHelper describe UserHelper do it 'should create opml item' do title = 'feed title' link = 'http://blog.fastladder.com/' feedlink = 'http://blog.fastladder.com/blog/rss.xml' feed = mock('feed') feed.should_receive(:title).and_return(title) feed.should_receive(:feedlink).and_return(feedlink) feed.should_receive(:link).and_return(link) item = mock('item') item.should_receive(:feed).and_return(feed) format_opml_item(item).should be_eql(%{<outline title="#{title.html_escape}" htmlUrl="#{link.html_escape}" type="rss" xmlUrl="#{feedlink.html_escape}" />}) end end
require_relative 'acceptance_helper' feature 'User can add list', %q{ In order to place your code, the Registered User may post it, Unregistered can only view }do given(:user) { create(:user) } # TODO need to find a solution for testing forms with CodeMirror, fill_in not working # scenario 'Authenticated user add your code' do # sign_in(user) # # visit lists_path # # click_on 'Post your code' # fill_in 'Title', with: 'New title' # fill_in 'Body', with: 'New Code' # click_on 'Create' # # expect(page).to have_content 'Your list code successfully created' # end scenario 'Non-Authenticated user add list code' do visit lists_path click_on 'Post your code' expect(page).to have_content 'You need to sign in or sign up before continuing.' end end
require 'spec_helper' describe Game do let (:game) {Game.new(date_played: '5-19-1983', event:'dbc floor tournament', site:'dbc floor', eco_code: 'C07')} context "#initialize" do it "creates a Game Object" do expect(game).to be_an_instance_of Game end it "should have a date" do expect(game.date_played).to eq('5-19-1983') end it "should have an event" do expect(game.event).to eq('dbc floor tournament') end it "should have a site" do expect(game.site).to eq('dbc floor') end it "should have an eco_code" do expect(game.eco_code).to eq('C07') end # it do # should allow_value('2013-01-01'). # for(:date_played). # on(:create) # end # it do # should allow_value('2013-??-??'). # for(:date_played). # on(:create) # end end context '#game_relationships' do it { should have_many(:participations) } it { should have_many(:moves) } it { should have_many(:players).through(:participations) } it { should have_many(:favorites) } end # context '#game_search' do # end end
class AddGroupRefToMembers < ActiveRecord::Migration[5.1] def change add_reference :members, :group, foreign_key: true end end
Write a method that takes a single String argument and returns a new string that contains the original value of the argument with the first character of every word capitalized and all other letters lowercase. You may assume that words are any sequence of non-blank characters. Examples word_cap('four score and seven') == 'Four Score And Seven' word_cap('the javaScript language') == 'The Javascript Language' word_cap('this is a "quoted" word') == 'This Is A "quoted" Word' Question: Write a method that takes a string input and outputs a new string that's modified with all words capitalized. Input vs Output: Input: string Output: new string Explicit vs Implicit Rules: Explicit: 1) All words within the string should be capitalized Implicit: 1) N/A Algorithm: word_cap method 1) invoke split and map method on string and set result to 'result' 2) within do..end, capitalize the word being iterated 3) invoke join method on 'result' def word_cap(str) result = str.split(' ').map do |word| word.capitalize end result.join(' ') end
require 'test_helper' class CommmentsControllerTest < ActionDispatch::IntegrationTest setup do @commment = commments(:one) end test "should get index" do get commments_url, as: :json assert_response :success end test "should create commment" do assert_difference('Commment.count') do post commments_url, params: { commment: { comment: @commment.comment, product_id: @commment.product_id, user_id: @commment.user_id } }, as: :json end assert_response 201 end test "should show commment" do get commment_url(@commment), as: :json assert_response :success end test "should update commment" do patch commment_url(@commment), params: { commment: { comment: @commment.comment, product_id: @commment.product_id, user_id: @commment.user_id } }, as: :json assert_response 200 end test "should destroy commment" do assert_difference('Commment.count', -1) do delete commment_url(@commment), as: :json end assert_response 204 end end
class UserPresenter < BasePresenter def first_name handle_none(user.first_name, '') do user.first_name end end def last_name handle_none(user.last_name, '') do user.last_name end end def full_name "#{first_name} #{last_name}" end def email handle_none user.email do user.email end end def phone_number handle_none(user.phone_number, '') do num = user.phone_number "#{num[0..2]}.#{num[3..5]}.#{num[6..9]}" end end def headline handle_none user.headline do content_tag(:div, render_markdown(user.headline), id: 'headline') end end def bio handle_none user.bio do content_tag(:div, render_markdown(user.bio), id: 'bio') end end def avatar content_tag :figure do handle_none(user.avatar, placeholder_image('200x280')) do image_tag user.avatar.asset_path_url end end end def resume handle_none(user.resume, '') do link_to 'resume', user.resume.asset_path_url, class: 'resume' end end def tweets content_tag :div, id: 'tweets' do username = user.connections.where(provider: 'twitter').first.try(:username) if username twitter_feed(username) end end end end
require File.join File.dirname(__FILE__), '../test_common.rb' class ZabbixPostTest < Test::Unit::TestCase def test_zabbix_is_running assert TestCommon::Process.running?('zabbix_server'), 'Zabbix server is not running!' end end
class CreateLeadershipRoles < ActiveRecord::Migration def change create_lookup_table :leadership_roles end end
require 'rails_helper' RSpec.describe LikesController, type: :controller do context 'guest user' do before do @user = FactoryGirl.create(:user) @topic = FactoryGirl.create(:topic) @bookmark = FactoryGirl.create(:bookmark) end describe 'POST create' do it 'redirects the user to the sign in view' do post :create, { bookmark_id: @bookmark.id} expect(response).to redirect_to(new_user_session_path) end end end context 'signed in user' do before do @user = FactoryGirl.create(:user) @user.confirm sign_in @user @topic = FactoryGirl.create(:topic) @bookmark = FactoryGirl.create(:bookmark) end describe 'POST create' do it 'creates a like for the current user and specified bookmark' do expect(@user.likes.find_by_bookmark_id(@bookmark_id)).to be_nil post :create, { bookmark_id: @bookmark.id } expect(@user.likes.find_by_bookmark_id(@bookmark.id)).not_to be_nil end end end end
require 'rails_helper' RSpec.describe "investigations/new", type: :view do before(:each) do assign(:investigation, Investigation.new( incident: nil, user: nil, report_number: "MyString", department: nil, status: "MyString", reportable_to_legal: false )) end it "renders new investigation form" do render assert_select "form[action=?][method=?]", investigations_path, "post" do assert_select "input[name=?]", "investigation[incident_id]" assert_select "input[name=?]", "investigation[user_id]" assert_select "input[name=?]", "investigation[report_number]" assert_select "input[name=?]", "investigation[department_id]" assert_select "input[name=?]", "investigation[status]" assert_select "input[name=?]", "investigation[reportable_to_legal]" end end end
class SessionsController < ApplicationController def create auth = Authorization.find_from_auth_hash(auth_hash) || Authorization.create_from_auth_hash(auth_hash) authenticate auth.user redirect_to dashboard_path end def auth_hash request.env['omniauth.auth'] end private def authenticate user session[:user_id] = user.id @current_user = user end end
class SearchController < ApplicationController before_action :authenticate_user! protect_from_forgery prepend: true def mk @base_url = "/search/mk" render :index end def index if params[:keywords].present? @keywords = params[:keywords] @user_id = current_user.id tool_search_terms = ToolSearchTerms.new(@keywords, @user_id) @tools = Tool.where( tool_search_terms.where_clause, tool_search_terms.where_args). order(tool_search_terms.order) @tools = @tools.includes(:user) else @tools = [] end respond_to do |format| format.html { redirect_to search_mk_path } format.json { render json: { tools: @tools.as_json(include: [:user]) } } end end end
# 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 # Add Yarn node_modules folder to the asset load path. Rails.application.config.assets.paths << Rails.root.join('node_modules') # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css ) Rails.application.config.assets.paths << Rails.root.join('vendor', 'assets', 'javascripts') Rails.application.config.assets.precompile += %w( .js .es6 ) # Rails.application.config.assets.precompile += %w( new.css ) # Rails.application.config.assets.precompile += %w( countdown.jquery.min.js ) # Rails.application.config.assets.precompile += %w( timer.js ) # Rails.application.config.assets.precompile += %w( jquery.validate.min.js ) # Rails.application.config.assets.precompile += %w( mail-script.js ) # Rails.application.config.assets.precompile += %w( jquery-3.3.1.slim.min.js ) # Rails.application.config.assets.precompile += %w( swiper.min.js ) # Rails.application.config.assets.precompile += %w( jquery.nice-select.min.js ) # Rails.application.config.assets.precompile += %w( masonry.pkgd.min.js ) # Rails.application.config.assets.precompile += %w( jquery.magnific-popup.js ) # Rails.application.config.assets.precompile += %w( wow.min.js ) # Rails.application.config.assets.precompile += %w( custom.js ) # Rails.application.config.assets.precompile += %w( jquery.easing.min.js ) # Rails.application.config.assets.precompile += %w( waypoints.min.js ) # Rails.application.config.assets.precompile += %w( masonry.pkgd.js ) # Rails.application.config.assets.precompile += %w( swiper_custom.js ) # Rails.application.config.assets.precompile += %w( owl.carousel.min.js ) # Rails.application.config.assets.precompile += %w( bootstrap.min.js ) # Rails.application.config.assets.precompile += %w( particles.min.js ) # Rails.application.config.assets.precompile += %w( jquery.ajaxchimp.min.js ) # Rails.application.config.assets.precompile += %w( contact.js ) # Rails.application.config.assets.precompile += %w( jquery-1.12.1.min.js ) # Rails.application.config.assets.precompile += %w( aos.js ) # Rails.application.config.assets.precompile += %w( gmaps.min.js ) # Rails.application.config.assets.precompile += %w( popper.min.js ) # Rails.application.config.assets.precompile += %w( slick.min.js ) # Rails.application.config.assets.precompile += %w( jquery.form.js ) # Rails.application.config.assets.precompile += %w( jquery.smooth-scroll.min.js ) # Rails.application.config.assets.precompile += %w( jquery.counterup.min.js )
# == Schema Information # # Table name: balances # # id :integer not null, primary key # total :integer default(0) # created_at :datetime not null # updated_at :datetime not null # user_id :integer # # Indexes # # index_balances_on_user_id (user_id) # # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :balance do user_id 1 total 1 end end
class ArtsController < ApplicationController before_action :authorize, only: [:new] def index @arts = Art.all @art = Art.where("title like ?", "Neueve") end def show @art = Art.find(params[:id]) end def edit @art = Art.find(params[:id]) end def update @art = Art.find(params[:id]) if @art.update_attributes(art_params) redirect_to art_index_path else render :edit end end def create @art = current_user.arts.new(art_params) if @art.save redirect_to art_index_path end end def new @art = Art.new end def delete @art = Art.find(params[:id]) if current_user != @art.user redirect_to art_index_path else @art.destroy redirect_to art_index_path end end private def art_params params.require(:art).permit(:name, :style, :price, :details, :avatar) end end
# frozen_string_literal: true module Ratings class Create < ActiveInteraction::Base integer :user_id integer :photopost_id def execute Rating.create!(user_id: user_id, photopost_id: photopost_id) end end end
require 'octokit' class UserFinder def initialize(opts = {}) @client = opts[:client] || Octokit::Client.new end def get_locations_for_usernames(usernames) usernames.map{ |username| @client.user(username) }.map{ |user| user[:location] } end end
module WastebitsClient class User < Base attr_accessor :id, :first_name, :last_name, :full_name, :email, :reset_password_sent_at, :reset_password_expires_at, :created_at, :updated_at, :confirmed_at, :scope, :settings, :is_locked, :locked_at, :is_super attr_writer :current_password, :password, :password_confirmation def save if valid? return self.class.post(self.access_token, '/users', :body => { :first_name => self.first_name, :last_name => self.last_name, :email => self.email}) end end def settings if @settings.instance_of?(String) JSON.parse(@settings) else (@settings || {}).to_hash end end def settings=(value) @settings = value end def update if valid? return self.class.put(self.access_token, "/users/#{self.id}", :body => { :first_name => self.first_name, :last_name => self.last_name, :email => self.email, :settings => self.settings.to_json, :is_locked => self.is_locked }) end end def update_password(current_password, password, password_confirmation) return self.class.put self.access_token, "/users/#{self.id}/password", :body => { :current_password => current_password, :password => password, :password_confirmation => password_confirmation } end def self.all(access_token, options={}) options = options.with_indifferent_access query = { :page => 1, :per_page => PER_PAGE }.with_indifferent_access query.merge!(options) get access_token, '/users', { :query => options } end def self.get_by_id(access_token, user_id) response = get(access_token, "/users/#{user_id.to_i}") if response[:meta][:code] == 200 response[:data][:access_token] = access_token return new(response[:data]) end end def self.get_by_email(access_token, email) response = get(access_token, "/users/email/#{email}") if response[:meta][:code] == 200 response[:data][:access_token] = access_token return new(response[:data]) end end def accounts self.class.get(self.access_token, "/users/#{self.id}/accounts") end def companies self.class.get(self.access_token, "/users/#{self.id}/companies") end end end
class Category < ApplicationRecord has_many :categorizes has_many :ideas, through: :categorizes end
# # = operators.rb - Operators for the BitString class # # Author:: Ken Coar # Copyright:: Copyright © 2010 Ken Coar # License:: Apache Licence 2.0 # # == Description # # Operator methods for <i>BitString</i> class (<i>e.g.</i>, those consisting # of special characters). # #-- # Copyright © 2010 Ken Coar # # 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. #++ #-- # Re-open the class to add the operator methods #++ class BitString # # === Description # # Perform a bitwise AND on the entire bitstring, returning a new # <i>BitString</i> object. The new bitstring will have the # same boundedness as the original. # # call-seq: # bitstring <i>& value</i> => <i>BitString</i> # bitstring.&<i>(value)</i> => <i>BitString</i> # # === Arguments # [<i>value</i>] <i>BitString</i>, <i>Integer</i>, or <i>String</i>. Value to AND with the bitstring. # # === Examples # bs = BitString.new('111111111') # nbs = bs & '111100011' # nbs.to_s # => "111100011" # # bs = BitString.new('10101010101', 11) # nbs = bs & '11110001111' # nbs.to_s # => "10100000101" # nbs = bs & '00001110000' # nbs.to_s # => "00001010000" # # === Exceptions # <i>None</i>. # def &(val) val = _arg2int(val) vMask = self.mask newval = (@value & val) & vMask bounded? ? self.class.new(newval, @length) : self.class.new(newval) end # def & # # === Description # # Perform a left-shift on the bitstring, returning a new <i>BitString</i> # containing the shifted value. If the bitstring is bounded, bits # shifted off the high end are lost. # # call-seq: # bitstring <i>&lt;&lt; bitcount</i> => <i>BitString</i> # bitstring.&lt;&lt;<i>(bitcount)</i> => <i>BitString</i> # # === Arguments # [<i>bitcount</i>] <i>Integer</i>. Number of positions by which to left-shift. # # === Examples # bs = BitString.new('1100111') # nbs = bs << 2 # nbs.to_s # => "110011100" # # bs = BitString.new('00010001', 8) # nbs = bs << 2 # nbs.to_s # => "01000100" # nbs = bs << 4 # nbs.to_s # => "00010000" # High bits shifted off and lost # # === Exceptions # <i>None</i>. # def <<(bits) value = @value * (2**bits.to_i) if (bounded?) self.class.new(value & self.mask, @length) else self.class.new(value) end end # def << # # === Description # # Right-shift the bitstring (toward the low end) by the specified number # of bits. Bits shifted off the end are lost; new bits shifted in at # the high end are 0. # # call-seq: # bitstring &gt;&gt; <i>bitcount</i> => <i>BitString</i> # bitstring.&gt;&gt;<i>(bitcount)</i> => <i>BitString</i> # # === Arguments # [<i>bitcount</i>] <i>Integer</i>. Number of positions to right-shift by. # # === Examples # bs = BitString.new('1100111') # nbs = bs >> 2 # nbs.to_s # => "11001" # # bs = BitString.new('00010001', 8) # nbs = bs >> 2 # nbs.to_s # => "00000100" # nbs = bs >> 4 # nbs.to_s # => "00000001" # # === Exceptions # <i>None</i>. # def >>(bits) value = @value / 2**bits.to_i if (bounded?) self.class.new(value, @length) else self.class.new(value) end end # def >> # # === Description # # Extract a particular substring from the bitstring. # If we're given a single index, we return an integer; if # a range, we return a new BitString. # # call-seq: # bitstring<i>[index]</i> => <i>Integer</i> # bitstring<i>[start, length]</i> => <i>BitString</i> # bitstring<i>[range]</i> => <i>BitString</i> # # === Arguments # [<i>index</i>] <i>Integer</i>. Single bit position. # [<i>start</i>] <i>Integer</i>. Start position of subset. # [<i>length</i>] <i>Integer</i>. Length of subset. # [<i>range</i>] <i>Range</i>. Subset specified as a range. # # === Examples # bs = BitString.new('110010110') # bs[0] # => 0 # bs[1] # => 1 # bs[0..1].to_s # Multi-bit indexing returns a bitsring # => "10" # bs[0,9].to_s # => "110010110" # bs[100..102].to_s # Can index 'way past the end for unbounded bitstrings # => "000" # # bs = BitString.new('110010110', 9) # bs[100..102].to_s # # => exception: "IndexError: index out of range" # # === Exceptions # [<tt>ArgumentError</tt>] If length specified with a range. # [<tt>IndexError</tt>] If bitstring is bounded and the substring is illegal. # def [](pos_p, length_p=nil) # # Turn a position/length into a range. # if (pos_p.kind_of?(Integer) && length_p.kind_of?(Integer)) pos_p = Range.new(pos_p, pos_p + length_p - 1) length_p = nil end if (pos_p.kind_of?(Range)) unless (length_p.nil?) raise ArgumentError.new('length not allowed with range') end pos_a = pos_p.to_a pos_a.reverse! if (pos_a.first < pos_a.last) r = pos_a.collect { |pos| self[pos].to_s } return self.class.new(r.join(''), r.length) end pos = pos_p.to_i # # Blow an error if we were given an index out of range. # unless ((pos >= 0) && ((! bounded?) || pos.between?(0, @length - 1))) _raise(OuttasightIndex, pos) end (@value & (2**pos)) / (2**pos) end # def [] # # === Description # # Set a bit or range of bits with a single operation. # # call-seq: # bitstring[<i>pos</i>] = <i>value</i> => <i>value</i> # bitstring[<i>start, length</i>] = <i>value</i> => <i>value</i> # bitstring[<i>range</i>] = <i>value</i> => <i>value</i> # # === Arguments # [<i>value</i>] <i>Array</i>, <i>BitString</i>, <i>Integer</i>, or <i>String</i>. Value (treated as a stream of bits) used to set the bitstring. # [<i>pos</i>] <i>Integer</i>. Single bit position to alter. # [<i>start</i>] <i>Integer</i>. First bit position in substring. # [<i>length</i>] <i>Integer</i>. Number of bits in substring. # [<i>range</i>] <i>Range</i>. Range of bits (<i>e.g.</i>, 5..10) to affect. # # === Examples # bs = BitString.new('110010110') # bs[0] = 1 # => 1 # bs.to_s # => "110010111" # bs[1] = 0 # => 0 # bs.to_s # => "110010101" # bs[0..3] = 14 # Multi-bit indexing set a bitsring # => "14" # bs.to_s # => "110011110" # bs[12..14] = 5 # => 5 # bs.to_s # => "101000110011110" # Can index past the end for unbounded bitstrings # # bs = BitString.new('110010110', 9) # bs[1,3] = 4095 # 111111111111, but gets truncated to low 3 bits # bs.to_s # => "110011110" # # === Exceptions # [<tt>ArgumentError</tt>] Both range and length specified, or value cannot be interpreted as an integer. # [<tt>IndexError</tt>] Non-integer or negative index, or beyond the end of the bitstring. # def []=(*args_p) low = high = width = nil args = args_p if (args.length == 2) # # [pos]= or [range]= # if ((r = args[0]).class.eql?(Range)) # # Convert into a [start,length] format to reuse that stream. # (start, stop) = [r.first, r.last].sort width = stop - start + 1 args = [start, width, args[1]] else args = [args[0], 1, args[1]] end elsif (args_p.length != 3) _raise(WrongNargs, args_p.length, 3) end # # Special cases of args have now been normalised to [start,length,value]. # Make sure the values are acceptable. # (start, nBits, value) = args _raise(BogoIndex, start) unless (start.respond_to?(:to_i)) start = start.to_i unless (start.kind_of?(Integer)) _raise(BogoIndex, nBits) unless (nBits.respond_to?(:to_i)) nBits = length.to_i unless (nBits.kind_of?(Integer)) highpos = start + nBits - 1 _raise(OuttasightIndex, highpos) if (bounded? && (highpos > @length - 1)) _raise(BitsRInts, value) unless (value.respond_to?(:to_i)) value = _arg2int(value) # # All the checking is done, let's do this thing. # vMask = 2**nBits - 1 fvalue = (value &= vMask) vMask *= 2**start value *= 2**start highpos = self.length bValue = @value & ((2**highpos - 1) & ~vMask) @value = bValue | value return fvalue end # def []= # # === Description # # Perform a bitwise exclusive OR (XOR) and return a copy of the # result. # # call-seq: # bitstring <i>^ value</i> => <i>BitString</i> # bitstring.^<i>(value)</i> => <i>BitString</i> # # === Arguments # [<i>value</i>] <i>Array</i>, <i>BitString</i>, <i>Integer</i>, or <i>String</i>. Value treated as a bitstream and exclusively ORed with the bitstring. # # === Examples # bs = BitString.new('110010110', 9) # nbs = bs ^ '001101001' # nbs.to_s # => "111111111" # nbs = bs ^ bs.mask # Equivalent to 'nbs = ~ bs' # nbs.to_s # => "001101001" # # === Exceptions # <i>None</i>. # def ^(value) value = _arg2int(value) value &= self.mask if (bounded?) bs = dup bs.from_i(value ^ bs.to_i) bs end # def ^ # # === Description # # Perform a bitwise inclusive OR with the current bitstring and # return a bitstring containing the result. # # call-seq: # bitstring <i>| value</i> => <i>BitString</i> # bitstring.|<i>(value)</i> => <i>BitString</i> # # === Arguments # [<i>value</i>] <i>Array</i>, <i>BitString</i>, <i>Integer</i>, or <i>String</i>. Value treated as a bitstream and inclusively ORed with the bitstring. # # === Examples # bs = BitString.new('110010110') # nbs = bs | '11000000000000000' # nbs.to_s # Bits cab be ORed in anywhere in an # => "11000000110010110" # unbouded string # # === Exceptions # <i>None</i>. # def |(value) value = _arg2int(value) value &= self.mask if (bounded?) bs = dup bs.from_i(value | bs.to_i) bs end # def | # # === Description # # Perform a one's complement on the current bitstring and return the # result in a new one. # # call-seq: # <i>~</i> bitstring => <i>BitString</i> # bitstring.~<i>()</i> => <i>BitString</i> # # === Arguments # <i>None</i>. # # === Examples # bs = BitString.new('110010110') # nbs = ~ bs # nbs.to_s # => "1101001" # Leading zeroes stripped when unbounded # # bs = BitString.new('110010110', 9) # nbs = ~ bs # nbs.to_s # => "001101001" # # bs = BitString.new('111111111') # nbs = ~ bs # nbs.to_s # => "0" # # bs = BitString.new('111111111', 9) # nbs = ~ bs # nbs.to_s # => "000000000" # # === Exceptions # <i>None</i>. # def ~() newval = (~ @value) & self.mask bounded? ? self.class.new(newval, @length) : self.class.new(newval) end # def ~ # # === Description # # Perform an equality check against another bitstring or representation # of one. The value and the boundedness must both match to be considered # equal. # # call-seq: # bitstring == <i>compstring</i> => <i>Boolean</i> # bitstring.==<i>(compstring)</i> => <i>Boolean</i> # # === Arguments # [<i>compstring</i>] <i>Array</i>, <i>BitString</i>, <i>Integer</i>, or <i>String</i>. Bitstring (or something representing one) against which to compare. # # === Examples # bs1 = BitString.new('111111111') # bs2 = BitString.new('111111111', 9) # bs1 == bs2 # => false # Boundedness doesn't match # # bs1 = BitString.new('111111111') # bs2 = BitString.new('111111111') # bs1 == bs2 # => true # Values and boundedness match # # bs1 = BitString.new('111111111') # bs1 == '111111111' # => true # When converted to an unbounded bitstring, it matches # # bs1 = BitString.new('111111111') # bs1 == '0000000111111111' # => true # When converted to an unbounded bitstring, it matches # # bs1 = BitString.new('111111111') # bs1 == 511 # => true # When converted to an unbounded bitstring, it matches # # bs1 = BitString.new('111111111', 9) # bs1 == '1000111111111' # => false # When converted to a bounded bitstring (because bs1 is), # # lengths and values don't match # # === Exceptions # <i>None</i>. # def ==(value) # # Bitstring/bitstring comparison # unless (value.class == self.class) value = _arg2int(value) if (self.bounded?) bits = [self.length, value.to_s(2).length].max value = self.class.new(value, bits) else value = self.class.new(value) end end ((self.class == value.class) && (self.bounded? == value.bounded?) && (self.length == value.length) && (@value == value.to_i)) end # def == end # class BitString
class PeopleController < ApplicationController def index @people = Person.all end def new @person = Person.new end def show @person = Person.find(params[:id]) @projects = @person.projects @no_associated_projects = @person.select_no_associated_projects end def create @person = Person.new(entry_params) if(@person.save) flash[:notice] = "Person created successfully" redirect_to(action: 'index', controller: 'people', person_id: @person.id) else flash[:alert] = "Something went wrong" render('new') end end def update person = Person.find(params[:id]) project = Project.find(params[:person][:projects]) if(!person.projects.find_by(id: params[:person][:projects])) person.projects << project end redirect_to(action: 'show', controller: 'people', person_id: person.id) end private def entry_params params.require(:person).permit(:name) end end
class MockApp def initialize @will_blocks = [] end def will(&block) @will_blocks << block end attr_accessor :results def run @results = [] begin self.start @will_blocks.each do |block| @results << block.call end rescue => e puts e.inspect puts e.backtrace.join("\n") end end end
Rails.application.routes.draw do mount RailsAdmin::Engine => '/admin', as: 'rails_admin' devise_for :users, :path_names => { :sign_up => 'sign_up', :sign_in => 'sign_in', :sign_out => 'sign_out', :password => 'password', }, controllers: { sessions: 'user/sessions', :registrations => 'user/registrations', :passwords => 'user/passwords'} devise_scope :user do #get 'user/sign_up' => 'user/registrations#sign_up', :as => :sign_up get 'user/sign_in' => 'user/sessions#sign_in' , :as => :sign_in end root to: "homes#index" resources :products get "user/dashboard" => "users#dashboard" , as: 'dashboard' get "products/like" => "products#like", as: 'like' get "/search" => "products#search" , as: :search_product post "/products/new" => "products#create" , as: :save_product patch "/products/edit/id" => "products#update" , as: :update_product get 'favourites/update' => "favourites#update" get 'favourites/favourites_details' => "favourites#favourites_details" , as: :favourites_details post 'checkout/create' => "checkout#create" get 'cancel' => "checkout#cancel" , as: :checkout_cancel get 'success' => "checkout#success" , as: :checkout_success # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html namespace :admin , path:'admin' do root to: "dashboards#index" end devise_for :admins, :path_names => { :sign_up => 'sign_up', :sign_in => 'sign_in', :sign_out => 'sign_out', :password => 'password', } end
require 'open-uri' require 'hpricot' class CrawlersController < ApplicationController layout 'index' # GET /crawlers def index @crawlers = Crawler.all render :layout => !request.xhr? end # GET /crawlers/1 def show @crawler = Crawler.find(params[:id]) @log_entries = @crawler.log_entries.paginate :page => params[:page] end def proceed crawlers = Crawler.find(:all, :conditions => ["start_at < ?", Time.new]) crawlers.each { |crawler| cralwer.start } pull_entry = CrawlerLog.find(:first, :conditions => ["status = ? and crawler_id = ?", :pull, params[:id]]) pull_entry.pull if pull_entry push_entry = CrawlerLog.find(:first, :conditions => ["status = ? and crawler_id = ?", :push, params[:id]]) push_entry.push if push_entry render :text => 'ok' end # GET /crawlers/new def new @crawler = Crawler.new end # GET /crawlers/1/edit def edit @crawler = Crawler.find(params[:id]) render :layout => !request.xhr? end def configuration @crawler = Crawler.find(params[:id]) render :text => '<pre>' + @crawler.config.to_yaml + '</pre>', :layout => !request.xhr? end def activate redirect_to crawlers_path and return unless request.post? crawler = Crawler.find(params[:id]) crawler.status = 'active' crawler.save flash[:notice] = t('crawlers.index.activated', :name => crawler.name) redirect_to crawlers_path end def deactivate redirect_to crawlers_path and return unless request.post? crawler = Crawler.find(params[:id]) crawler.status = 'inactive' crawler.save flash[:notice] = t('crawlers.index.deactivated', :name => crawler.name) redirect_to crawlers_path end def run redirect_to crawlers_path and return unless request.post? crawler = Crawler.find(params[:id]) crawler.running = true crawler.save flash[:notice] = t('crawlers.index.started', :name => crawler.name) redirect_to crawlers_path end def proxy render :layout => false and return if params[:url].blank? url_param = params[:url] url_param = "http://#{url_param}" if url_param && !url_param.start_with?('http') url = URI.parse(url_param) domain = (url.scheme.blank? ? "http://" : "#{url.scheme}://") + url.host doc = Hpricot(open(url)) doc.search('script').remove doc.search('link') do |stylesheet| stylesheet['href'] = domain + stylesheet['href'] end doc.search('a') do |link| link['href'] = 'proxy?url=' + CGI::escape(domain + link['href']) unless link['href'].blank? end doc.search('img') do |image| image['src'] = domain + image['src'] end render :text => doc.to_html end # POST /crawlers # POST /crawlers/new def create @crawler = Crawler.new(params[:crawler]) if @crawler.save redirect_to(edit_crawler_path(@crawler), :notice => 'Crawler was successfully created.') else render :action => "new" end end # PUT /crawlers/1 def update @crawler = Crawler.find(params[:id]) respond_to do |format| if @crawler.update_attributes(params[:crawler]) format.html { redirect_to(@crawler, :notice => 'Crawler was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @crawler.errors, :status => :unprocessable_entity } end end end def import @crawler = Crawler.find(params[:id]) @crawler.config = YAML.load(params[:crawler][:config]).to_options if @crawler.save! flash[:notice] = "Crawler configuration imported successfully" end rescue flash[:error] = "Crawler configuration YAML was incorrect. Import failed." ensure redirect_to :action => :edit end # DELETE /crawlers/1 # DELETE /crawlers/1.xml def destroy @crawler = Crawler.find(params[:id]) @crawler.destroy respond_to do |format| format.html { redirect_to(crawlers_url) } format.xml { head :ok } end end def start @crawler = Crawler.find(params[:id]) @crawler.start redirect_to crawler_path(@crawler) end def stop @crawler = Crawler.find(params[:id]) @crawler.stop redirect_to crawler_path(@crawler) end def reset @crawler = Crawler.find(params[:id]) @crawler.reset redirect_to crawler_path(@crawler) end end
require 'rails_helper' RSpec.describe Proposal, :type => :model do describe "Create valid review" do it "should be permitted" do u = User.create(:email => 'prova1@example.it', :username => 'user1', :password => 'useruser') r = UserReview.create(:rating => 5, :comment => 'Ciao', :user => u) expect(r).to be_valid end end describe "Create valid review" do it "should be permitted" do u = User.create(:email => 'prova1@example.it', :username => 'user1', :password => 'useruser') r = UserReview.create(:rating => 1, :comment => 'Questa è una recensione', :user => u) expect(r).to be_valid end end describe "Create invalid review" do it "shouldn't be permitted" do u = User.create(:email => 'prova1@example.it', :username => 'user1', :password => 'useruser') r = UserReview.create(:comment => 'Questa è una recensione', :user => u) expect(r).not_to be_valid end end describe "Create invalid review" do it "shouldn't be permitted" do u = User.create(:email => 'prova1@example.it', :username => 'user1', :password => 'useruser') r = UserReview.create(:rating => 1, :user => u) expect(r).not_to be_valid end end describe "Create invalid review" do it "shouldn't be permitted" do u = User.create(:email => 'prova1@example.it', :username => 'user1', :password => 'useruser') r = UserReview.create(:rating => 1) expect(r).not_to be_valid end end describe "Create invalid review" do it "shouldn't be permitted" do u = User.create(:email => 'prova1@example.it', :username => 'user1', :password => 'useruser') r = UserReview.create(:rating => 'ciao', :comment => 'Questa è una recensione', :user => u) expect(r).not_to be_valid end end describe "Create invalid review" do it "shouldn't be permitted" do u = User.create(:email => 'prova1@example.it', :username => 'user1', :password => 'useruser') r = UserReview.create(:rating => 10, :comment => 'Questa è una recensione', :user => u) expect(r).not_to be_valid end end end
class TechnikGrid < MyGrid def configure(c) super c.model = "Technik" c.columns= [:name] end end
ActiveAdmin.register Experience do permit_params :id, :name, :logo, :photo, :hours, :phone, :address, :body, :caption, events_attributes: [:id, :name, :date, :time, :location, :body, :_destroy] config.filters = false controller do def find_resource scoped_collection.friendly.find(params[:id]) end end index do selectable_column column :logo column :name actions end form do |f| f.inputs "Experience Details" do f.input :name f.input :body f.input :hours f.input :address f.input :phone f.input :logo, :as => :file, :hint => f.template.image_tag(f.object.logo.url(:admin_thumb)) f.input :photo f.input :caption f.has_many :events, :allow_destroy => true, :heading => "Featured Event" do |ff| ff.input :name ff.input :date ff.input :time ff.input :location ff.input :body end end f.actions end end
# frozen_string_literal: true module SC::Billing::Subscriptions class UpdateOperation < ::SC::Billing::Subscriptions::CreateOperation attr_accessor :subscription private :subscription def initialize(subscription:, **args) self.subscription = subscription super(args) end def call(data, **extra_params) subscription.update(subscription_params(data, extra_params)) end end end
# # Cookbook Name:: dockworker # Recipe:: provisioner # # Copyright 2012-2014, 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. # include_recipe 'docker' package "linux-image-extra-#{node[:kernel][:release]}" do notifies :restart, 'service[docker]', :immediately end registry_password = Chef::DataBagItem.load("docker", "auth") docker_registry 'https://index.docker.io/v1/' do email 'testaws199@gmail.com' username 'jaibapna' password registry_password['registry_pwd'] cmd_timeout 360 end docker_image 'docker-demo' do retries 2 tag 'latest' action :pull_if_missing end
class List < ActiveRecord::Base ACTIVE = ['Y','N'] RESETS = ["0900","1000","1100","1200","1300","1400","1500","1600","1700","1800","1900","2000"] validates :list_id, presence: true, length: { in: 3..8 }, numericality: { only_integer: true } validates :list_name, presence: true, length: { in: 2..20 } validates :active, presence: true validates :campaign_id, presence: true validates :reset_time, format: { with: /([0-9]{4})?(-[0-9]{4})*/, message: "24hr clock times seperated by - only" } belongs_to :campaign has_many :leads attr_accessor :dialable attr_accessor :leads def campaign_name self.campaign.campaign_name if self.campaign end def leads Lead.where(:list_id => self.list_id).count end def dialable @list_statuses = self.campaign.dial_statuses.split(" ") Lead.where(list_id: self.id).where(status: @list_statuses).where("called_since_last_reset = 'N'").count end end
require 'spec_helper' describe GithubAuthorizedKeys::CLI do before do @config = { 'organization' => 'some-org', 'oauth_token' => 'token' } subject.stub(:load_config) subject.stub(:fetch_members => [ {'login'=>'first'}, {'login'=>'second'}, {'login'=>'third'} ]) subject.stub(:fetch_keys).and_return( [{'key' => 'ssh-rsa 1'}], [{'key' => 'ssh-rsa 2'}], [{'key' => 'ssh-rsa 3'},{'key' => 'ssh-rsa 4'}] ) end it "will spit out the original authorized_keys file on error" do subject.stub(:read_original_authorized_keys => 'original authorized keys') subject.run('nonexistant').should == 'original authorized keys' end it "is ok that there were no provided additional keys" do subject.stub(:config => @config) expected = [ '### THIS FILE IS AUTOMATICALLY GENERATED', '# first', 'ssh-rsa 1', '# second', 'ssh-rsa 2', '# third', 'ssh-rsa 3', 'ssh-rsa 4' ].join("\n") subject.run(nil).should == expected end it "generates a proper authorized_keys file" do @config.merge!({'additional_keys'=>['ssh-rsa a','ssh-rsa b']}) subject.stub(:config => @config) expected = [ '### THIS FILE IS AUTOMATICALLY GENERATED', 'ssh-rsa a', 'ssh-rsa b', '# first', 'ssh-rsa 1', '# second', 'ssh-rsa 2', '# third', 'ssh-rsa 3', 'ssh-rsa 4' ].join("\n") subject.run(nil).should == expected end end
# Build the HTML tag method def tag(tag_name, value, attributes = {}) html_attrs = attributes.map do |key, value| " #{key}='#{value}'" end "<#{tag_name}#{html_attrs.join(' ')}>#{value}</#{tag_name}>" end puts tag("h1", "Hello world") # => <h1>Hello world</h1> puts tag("h1", "Hello world", { class: "bold" }) # => <h1 class='bold'>Hello world</h1> puts tag("a", "Le Wagon", { href: "http://lewagon.org", class: "btn" }) # => <a href='http://lewagon.org' class='btn'>Le Wagon</a>
# frozen_string_literal: true Puppet::Util::Log.newdesttype :logging do match "Logging::Logger" # Bolt log levels don't match exactly with Puppet log levels, so we use # an explicit mapping. def initialize(logger) @external_logger = logger @log_level_map = { debug: :debug, info: :info, notice: :notice, warning: :warn, err: :error, # Nothing in Puppet actually uses alert, emerg or crit, so it's hard to say # what they indicate, but they sound pretty bad. alert: :error, emerg: :fatal, crit: :fatal } end def handle(log) @external_logger.send(@log_level_map[log.level], log.to_s) end end
class LabirintController < ApplicationController layout false, except: [:index] def parse @flights = Parser.parse(params[:date_from], params[:date_to]) end end
require 'rspec' require 'logic_gates' describe '#my_and' do it "matches truth table" do expect(my_and(false, false)).to be_falsey expect(my_and(false, true)).to be_falsey expect(my_and(true, false)).to be_falsey expect(my_and(true, true)).to be_truthy end end describe '#my_or' do it "matches truth table" do expect(my_or(false, false)).to be_falsey expect(my_or(false, true)).to be_truthy expect(my_or(true, false)).to be_truthy expect(my_or(true, true)).to be_truthy end end describe '#not' do it "matches truth table" do expect(not(false)).to be_truthy expect(not(true)).to be_falsey end end describe '#xor' do it "matches truth table" do expect(xor(false, false)).to be_falsey expect(xor(false, true)).to be_truthy expect(xor(true, false)).to be_truthy expect(xor(true, true)).to be_falsey end end describe '#nor' do it "matches truth table" do expect(nor(false, false)).to be_truthy expect(nor(false, true)).to be_falsey expect(nor(true, false)).to be_falsey expect(nor(true, true)).to be_falsey end end describe '#nand' do it "matches truth table" do expect(nand(false, false)).to be_truthy expect(nand(false, true)).to be_truthy expect(nand(true, false)).to be_truthy expect(nand(true, true)).to be_falsey end end describe '#xnor' do it "matches truth table" do expect(xnor(false, false)).to be_truthy expect(xnor(false, true)).to be_falsey expect(xnor(true, false)).to be_falsey expect(xnor(true, true)).to be_truthy end end describe '#mux' do it "matches truth table" do expect(mux(false, false, false)).to be_falsey expect(mux(false, true, false)).to be_falsey expect(mux(true, false, false)).to be_truthy expect(mux(true, true, false)).to be_truthy expect(mux(false, false, true)).to be_falsey expect(mux(false, true, true)).to be_truthy expect(mux(true, false, true)).to be_falsey expect(mux(true, true, true)).to be_truthy end end
require 'sinatra' require 'securerandom' require 'json' require 'liquid' configure { set :server, :puma } COLUMNS = { 'ergodox_ez' => [7,7,6,7,5,2,1,3,7,7,6,7,5,2,1,3], 'planck' => [12,12,12,11], 'preonic' => [12,12,12,12,12] } post '/' do layout = JSON.load(request.body.read) type = layout['type'] uuid = SecureRandom.uuid() tpl = File.read("./templates/#{type}.liquid") c_file = Liquid::Template.parse(tpl).render({'columns' => COLUMNS[type], 'layout' => layout}) # TODO: Commenting these out, for now - makes testing faster, but will wreak havoc # Also - cp is very slow # `cp -r qmk_firmware /tmp/#{uuid}` #output_file = "/tmp/#{uuid}/keyboard/#{type}/keymaps/keymap_#{uuid}.c" output_file = "qmk_firmware/keyboard/#{type}/keymaps/keymap_#{uuid}.c" f = File.new(output_file, 'w') f.write(c_file) f.close `cd qmk_firmware/keyboard/#{type} && make KEYMAP="#{uuid}"` status = 200 begin hex = File.read("qmk_firmware/keyboard/#{type}/#{type}.hex") rescue Errno::ENOENT status = 400 end headers = { 'Content-Disposition' => "attachment;filename=#{type}.hex", 'Content-Type' => 'application/octet-stream' } [status, headers, hex] end
# frozen_string_literal: true FactoryGirl.define do factory :user do email { Faker::Internet.email } password { Faker::Internet.password } profile { |r| r.association :profile } role { %i[client admin].sample } end end
# outer scope variables can be accessed by inner scope a = 1 # outer scope variable loop do # the block following the invocation of the `loop` method creates an inner scope puts a # => 1 a = a + 1 # "a" is re-assigned to a new value break # necessary to prevent infinite loop end puts a # => 2 "a" was re-assigned in the inner scope # inner scope variables cannot be accessed in outer scope loop do # the block following the invocation of the `loop` method creates an inner scope b = 1 break end puts b # => NameError: undefined local variable or method `b' for main:Object # peer scopes do not conflict 2.times do a = 'hi' puts a # 'hi' <= this will be printed out twice due to the loop end loop do puts a # => NameError: undefined local variable or method `a' for main:Object break end puts a # => NameError: undefined local variable or method `a' for main:Object # Nested Blocks a = 1 # first level variable loop do # second level b = 2 loop do # third level c = 3 puts a # => 1 puts b # => 2 puts c # => 3 break end puts a # => 1 puts b # => 2 puts c # => NameError break end puts a # => 1 puts b # => NameError puts c # => NameError # variable shadowing [1, 2, 3].each do |n| puts n end # But what if we have a varialbe also called n in the outer scope?: n = 10 [1, 2, 3].each do |n| puts n # outer scope variable (n = 10) is ignored and n here is in reference to the parameter |n| end # Variable shadowing also prevents us from making changes to the outer scope variable n: n = 10 1.times do |n| n = 11 end puts n # => 10
class Icon < ApplicationRecord CATEGORIES = ["Music", "Sports", "Business", "Food", "Politics", "Science", "Design", "Writing", "Cinema", "Code"] has_many :bookings, dependent: :destroy has_many :reviews, through: :bookings, dependent: :destroy belongs_to :user has_one_attached :photo validates :name, :price, :location, :category, :description, presence: true validates :description, length: { minimum: 10 } validates :category, inclusion: { in: CATEGORIES } geocoded_by :location after_validation :geocode, if: :will_save_change_to_location? include PgSearch::Model pg_search_scope :search_by_location_and_category, against: [:location, :category], using: { tsearch: { prefix: true } } def average_rating ratings = self.reviews.map do |review| review.rating end verdict = ratings.inject { |sum, el| sum + el }.to_f / ratings.size verdict.round(2) end end
class CreateFlashphotoBanners < ActiveRecord::Migration def self.up create_table :flashphoto_banners do |t| t.integer "article_banner_id" t.timestamps end add_index :flashphoto_banners, [:article_banner_id], :name => 'flashphoto_banners_article_banner_id_index' end def self.down drop_table :flashphoto_banners end end
# frozen_string_literal: true require 'ostruct' RSpec.describe Api::V1::HoursController, type: :controller do let(:valid_json) do { "2016-01-02 00:00:00 -0800": { open: '12:00am', close: '12:00pm', string_date: '2016-01-02', sortable_date: '2016-01-02', formatted_hours: '2016-01-02 00:00:00 -0800', open_all_day: true, closes_at_night: false }, "2016-01-03 00:00:00 -0800": { open: '12:00am', close: '12:00pm', string_date: '2016-01-03', sortable_date: '2016-01-03', formatted_hours: '2016-01-03 00:00:00 -0800', open_all_day: true, closes_at_night: false }, "2016-01-05 00:00:00 -0800": { open: '12:00am', close: '12:00pm', string_date: '2016-01-05', sortable_date: '2016-01-05', formatted_hours: '2016-01-05 00:00:00 -0800', open_all_day: true, closes_at_night: false } } end let(:valid_attributes) do # A Date that covers each of the three types of Drupal*Hour { dates: ['2016-01-02', '2016-01-03', '2016-01-05'] } end context 'with valid hours' do before do ENV['API_URI'] = 'http://server' ENV['API_ROUTE'] = '/action.json' stub_request(:post, 'http://server/action.json').to_return(status: 200, body: valid_json.to_json, headers: {}) post :show, params: valid_attributes end it 'returns all hours' do expect(JSON.parse(response.body).keys).to include('2016-01-02 00:00:00 -0800', '2016-01-03 00:00:00 -0800', '2016-01-05 00:00:00 -0800') end it 'returns normal hours' do expect(response.body).to include('2016-01-02') expect(JSON.parse(response.body)['2016-01-02 00:00:00 -0800']['open']).to eq('12:00am') expect(JSON.parse(response.body)['2016-01-02 00:00:00 -0800']['close']).to eq('12:00pm') end end end
class HomeController < ApplicationController def index @states = Game.all respond_to do |format| format.html {render :index} format.json {render json: @states} end end def show @state = Game.find(params[:id]) render json: @state end def save @state = Game.create(save_params) render json: @state, status: 201 end private def save_params params.require(:game).permit({state: []}) end end
module PuppetX module BSD class Util def self.normalize_config(config) # Modify the config object to reject all undef values raise ArgumentError, "Config object must be a Hash" unless config.is_a? Hash config.reject!{|k,v| k == :undef or v == :undef } config.reject!{|k,v| k == :nil or v == :nil } end def self.validate_config(config,required_items,optional_items) # Ensure that all of the required params are passed, and that the rest # of the options requested are valid raise ArgumentError, "Config object must be a Hash" unless config.is_a? Hash required_items.each do |k,v| unless config.keys.include? k raise ArgumentError, "#{k} is a required configuration item" end end config.each do |k,v| unless required_items.include? k or optional_items.include? k raise ArgumentError, "unknown configuration item found: #{k}" end end end def self.uber_merge(h1, h2) h2.keys.each {|key| # Move the keys that won't clobber from h2 to h1 if not h1.keys.include? key h1[key] = h2[key] h2.delete(key) end } h1.keys.each {|key| # Move more complicated keys from h2 to h1 if not h2.keys.include? key next elsif h1[key].is_a? Hash and h2[key].is_a? Hash h1[key] = self.uber_merge(h1[key], h2[key]) next elsif h1[key].is_a? Array h1[key] << h2[key] h1[key].flatten! next else # key values conflict and should be combined unless h1[key] == h2[key] h1[key] = Array([h1[key], h2[key]]).flatten end end } h1 end end end end
require 'spec_helper' describe 'python::virtualenv' do let(:title) { '/opt/v' } on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) { facts } context 'with python3' do three_versions(facts).each do |three_version| context "version #{three_version}" do if three_version.nil? puts "skipping python3 tests on #{facts[:os]}" next end let :pre_condition do " class {'python': version => '#{three_version}', virtualenv => true, } " end case facts[:osfamily] when 'OpenBSD' it do is_expected.to contain_exec('python_virtualenv_/opt/v').with_command( # /virtualenv-3\s+-p\spython-#{short_version}\s\/opt\/v/ %r{virtualenv-3\s+-p\spython\s\/opt\/v} ) end when 'FreeBSD' case three_version when '34' it do is_expected.to contain_exec('python_virtualenv_/opt/v').with_command( %r{virtualenv-3.4\s+-p\spython\s\/opt\/v} ) end when '35' it do is_expected.to contain_exec('python_virtualenv_/opt/v').with_command( %r{virtualenv-3.5\s+-p\spython\s\/opt\/v} ) end end else it { is_expected.to contain_python__virtualenv('/opt/v') } it do is_expected.to contain_exec('python_virtualenv_/opt/v').with_command( # /virtualenv-3\s+-p\spython-#{short_version}\s\/opt\/v/ %r{virtualenv\s+-p\spython\s\/opt\/v} ) end end end end end end end end
require "open3" require "safe_shell/version" require "safe_shell/mock" module SafeShell class << self def make_context(constants, libraries) { :constants => constants, :libraries => [libraries].flatten } end def run_test(test, cmd_test, mocks = []) variables = test[:constants].map{ |name, value| "#{name}=#{value}" } libs = test[:libraries].map{ |lib| "source #{lib}"} variables << 'SS_UNDER_TESTING=true' cmd = variables + libs + mocks cmd << cmd_test # `bash -c '#{cmd.join(' ; ')}'` safe_run(cmd) end def safe_run(cmds) stdout_err, status = Open3.capture2e("bash -c '#{cmds.join('; ')}'") raise 'Error in your script: ' + stdout_err if status.exitstatus.nonzero? stdout_err.strip end end end
require "optparse" class Sable::Runner DEFAULT_SAFILE = 'SAFile' def run(argv) mode = nil dry_run = false options = { file: DEFAULT_SAFILE } output = DEFAULT_SAFILE opt.on('-a', '--apply') { mode = :apply } opt.on('', '--dry-run') { dry_run = true } opt.on('-e', '--export') do mode = :export options.delete(:file) end opt.on('-o', '--output=FILE') {|v| output = v } opt.parse!(argv) client = Sable::Client.new(options) case mode when :apply client.apply(dry_run) when :export client.export(output) end return 0 end def opt @opt ||= OptionParser.new end end
class ScienceQuestionsController < ApplicationController def index @questions = ScienceQuestionsFetchService.new.random_questions_list rescue # NOTE: the standard error page will render when any error is raised, regardless of the type of error # Will need to change this in the future for more nuanced error handling render "shared/error" end end
require_relative './dings' module AnsiClr include Dings OP = 27.chr + '[' # ANSI color control opening symbols PLAIN = '0' RESET = "#{OP}m" # Styles: BOLD = '1' DIM = '2' ULINE = '4' BLINK = '5' REVERSE = '7' HIDDEN = '8' REBOLD = "2#{BOLD}" REDIM = "2#{DIM}" REULINE = "2#{ULINE}" REBLINK = "2#{BLINK}" REREVERSE = "2#{REVERSE}" REHIDDEN = "2#{HIDDEN}" # Foregrounds: F_DEF = '39' F_BLACK = '30' F_RED = '31' F_GREEN = '32' F_BROWN = '33' F_YELLOW = F_BROWN F_BLUE = '34' F_PURPLE = '35' F_MAGENTA = F_PURPLE F_CYAN = '36' F_LGREY = '37' F_LGRAY = F_LGREY F_DGREY = '90' F_DGRAY = F_DGREY F_LRED = '91' F_LGREEN = '92' F_LBROWN = '93' F_LYELLOW = F_LBROWN F_LBLUE = '94' F_LPURPLE = '95' F_LMAGENTA = F_LPURPLE F_LCYAN = '96' F_WHITE = '97' CL = 'm' B_BLACK = '40' B_RED = '41' B_GREEN = '42' B_BROWN = '43' B_YELLOW = B_BROWN B_BLUE = '44' B_PURPLE = '45' B_MAGENTA = B_PURPLE B_CYAN = '46' B_LGREY = '47' B_LGRAY = B_LGREY B_DGREY = '100' B_DGRAY = B_DGREY B_PLAIN = '49' B_DEFAULT = B_PLAIN B_LRED = '101' B_LGREEN = '102' B_LBROWN = '103' B_LYELLOW = B_LBROWN B_LBLUE = '104' B_LPURPLE = '105' B_LMAGENTA = B_LPURPLE B_LCYAN = '106' B_WHITE = '107' STYLES = { BOLD => 'BOLD', DIM => 'DIM', ULINE => 'ULINE', BLINK => 'BLINK', REVERSE => 'REVERSE', HIDDEN => 'HIDDEN', REBOLD => 'RE-BOLD', REDIM => 'RE-DIM', REULINE => 'RE-ULINE', REBLINK => 'RE-BLINK', REREVERSE => 'RE-REVERSE', REHIDDEN => 'RE-HIDDEN' } FORES = { F_DEF => 'F_DEF', F_BLACK => 'F_BLACK', F_RED => 'F_RED', F_GREEN => 'F_GREEN', F_BROWN => 'F_BROWN', F_BLUE => 'F_BLUE', F_PURPLE => 'F_PURPLE', F_CYAN => 'F_CYAN', F_LGREY => 'F_LGREY', F_DGREY => 'F_DGREY', F_LRED => 'F_LRED', F_LGREEN => 'F_LGREEN', F_LBROWN => 'F_LBROWN', F_LBLUE => 'F_LBLUE', F_LPURPLE => 'F_LPURPLE', F_LCYAN => 'F_LCYAN', F_WHITE => 'F_WHITE', } BACKS = { B_BLACK => 'B_BLACK', B_RED => 'B_RED', B_GREEN => 'B_GREEN', B_BROWN => 'B_BROWN', B_BLUE => 'B_BLUE', B_PURPLE => 'B_PURPLE', B_CYAN => 'B_CYAN', B_LGREY => 'B_LGREY', B_DGREY => 'B_DGREY', B_DEFAULT => 'B_DEFAULT', B_LRED => 'B_LRED', B_LGREEN => 'B_LGREEN', B_LBROWN => 'B_LBROWN', B_LBLUE => 'B_LBLUE', B_LPURPLE => 'B_LPURPLE', B_LCYAN => 'B_LCYAN', B_WHITE => 'B_WHITE', } def test puts out = '' BACKS.keys.each { |b| FORES.keys.each { |f| STYLES.keys.each { |s| out << %<#{LLQBIG}#{OP}#{s};#{f};#{b}m#{FORES[f]}/#{BACKS[b]}:#{STYLES[s]}#{RESET}#{RRQBIG}> if out.length > 240 # accounting for non-visual symbols puts out out = '' end } } print "\n" } puts end module_function :test end
class Bid < ActiveRecord::Base belongs_to :sale belongs_to :user before_validation :default_to_zero_if_necessary, :on => :create before_validation :check_if_active, :on => :create before_validation :check_if_begun, :on => :create validates :price, uniqueness: {scope: :sale_id} validate :more_than_min after_create :inc_min def total_bid price * sale.quantity end private def more_than_min if self.price < sale.minimum errors.add(:price, "Your bid must be more than the minimum / last bid.") end end def default_to_zero_if_necessary self.price = 0 if self.price.blank? end def inc_min sale.update_attributes(:minimum => price) end def check_if_active if sale.sale_end < Time.zone.now errors.add(:price, "The auction has ended.") end end def check_if_begun if sale.sale_begin > Time.zone.now errors.add(:price, "The auction has not started yet.") end end end
class UserMailer < ApplicationMailer def confirmation(user) @user = user mail(to: user.email, subject: 'Please confirm your email') end def notification(user, message, link) @user = user @message = message # 'root' links to the root_url if they're relative link = root_url + link[1..link.length] if link.starts_with?('/') @link = link @unsubscribe_link = edit_user_url(user) headers['List-Unsubscribe'] = "<#{@unsubscribe_link}>" mail(to: user.email, subject: 'New Notification') end end
Rails.application.routes.draw do resources :authors do member do get 'view_books' end end resources :books root "authors#index" end
class Unit class DeadError < StandardError end attr_reader :attack_power, :health_points def initialize(health_points, attack_power) @health_points = health_points @attack_power = attack_power end def attack!(enemy) can_attack?(enemy) enemy.damage(@attack_power) end def damage(amount) @health_points -= amount end def dead? health_points <= 0 end def can_attack?(enemy) raise DeadError, "You're dead!" if self.dead? raise DeadError, "Attacking a dead person is not nice!" if (!enemy.is_a?(Barracks) && enemy.dead?) end end
class Customer attr_reader :name, :downloads def initialize name @name = name @downloads = [] end def add_download arg @downloads << arg end def statement result = "\nDownload Records for #{name}\n" @downloads.each do |element| result += "\t" +element.song.title+ " " + element.charge.to_s + "\n" end result += "Amount owed is #{total_charge}\n" result += "You earned #{new_release_download_points} point(s)" result end private def amount_for download download.charge end def total_charge @downloads.inject(0) { |sum, element| sum + element.charge } end def new_release_download_points @downloads.inject(0) do |sum, element| sum + element.new_release_download_points end end end
require 'nokogiri' require 'open-uri' Dir[File.join(Rails.root, 'lib', 'game_modules', '*.rb')].each do |f| require File.expand_path(f) end class Game < ActiveRecord::Base belongs_to :user scope :unfinished, where(:ended_at => nil) scope :others_turn, where(:my_turn => false) scope :my_turn, where(:my_turn => true) def refresh_status Resque.enqueue(UpdateGame, self.id) end def refresh_status! my_turn! if game_module.my_turn?(doc, username) end def doc Nokogiri::HTML(open(url)) end def username user.username end def nickname game_module.nickname end def game_module case url when /boardgamegeek.com\/tigris/ BGGTigris when /go.davepeck.org\/play/ DavePeckGo when /brass.orderofthehammer.com/ HammerBrass else nil end end def played! self.my_turn = false save! end def as_json(options={}) super(:methods => [ :nickname ]) end private def my_turn! self.my_turn = true save! end end
class ProduitApi< ActionWebService::API::Base api_method :find_all_produits, :returns => [[:int]] api_method :find_produit_by_id, :expects => [:int], :returns => [Produit] end
require 'RMagick' module Thumbo class Proxy attr_reader :title def initialize owner, title @owner, @title = owner, title @image = nil # please stop warning me @image is not defined end # image processing def image @image || (self.image = read_image) end # check if image exists in memory def image? @image end def image_with_timeout time_limit = 5 @image || (self.image = read_image_with_timeout(time_limit)) end def image= new_image release @image = new_image end # is this helpful or not? def release @image = nil GC.start self end # e.g., # thumbnails[:original].from_blob uploaded_file.read def from_blob blob, &block self.image = Magick::ImageList.new.from_blob(blob, &block) self end def to_blob &block self.image.to_blob(&block) end # convert format to website displable image format def convert_format_for_website image.format = 'PNG' unless ['GIF', 'JPEG'].include?(image.format) end # create thumbnails in the image list (Magick::ImageList) def create return if title == :original release limit = owner.class.thumbo_common[title] if limit create_common(limit) else limit = owner.class.thumbo_square[title] create_square(limit) end self end def write filename = nil, &block storage.write(filename || self.filename, to_blob(&block)) end # delegate all def method_missing msg, *args, &block raise 'fetch image first if you want to operate the image' unless @image if image.__respond_to__?(msg) # operate ImageList, a dirty way because of RMagick... [image.__send__(msg, *args, &block)] elsif image.first.respond_to?(msg) # operate each Image in ImageList image.to_a.map{ |layer| layer.__send__(msg, *args, &block) } else # no such method... super(msg, *args, &block) end end # storage related def storage owner.class.thumbo_storage end def paths storage.paths(filename) end def delete storage.delete(filename) end # owner delegate def filename owner.thumbo_filename self end def uri owner.thumbo_uri self end # attribute def dimension img = image.first [img.columns, img.rows] end def mime_type image.first.mime_type end def fileext if @image case ext = image.first.format when 'PNG8'; 'png' when 'PNG24'; 'png' when 'PNG32'; 'png' when 'GIF87'; 'gif' when 'JPEG'; 'jpg' when 'PJPEG'; 'jpg' when 'BMP2'; 'bmp' when 'BMP3'; 'bmp' when 'TIFF64'; 'tiff' else; ext.downcase end elsif owner.respond_to?(:thumbo_default_fileext) owner.thumbo_default_fileext else raise "please implement #{owner.class}\#thumbo_default_fileext or Thumbo can't guess the file extension" end end protected attr_reader :owner def create_common limit # can't use map since it have different meaning to collect here self.image = owner.thumbos[:original].image.collect{ |layer| # i hate column and row!! nerver remember which is width... new_dimension = Thumbo.calculate_dimension(limit, layer.columns, layer.rows) # no need to scale if new_dimension == dimension(layer) layer # scale to new_dimension else layer.scale(*new_dimension) end } end def create_square limit self.image = owner.thumbos[:original].image.collect{ |layer| layer.crop_resized(limit, limit).enhance } end private # fetch image from storage to memory # raises Magick::ImageMagickError def read_image Magick::ImageList.new.from_blob(storage.read(filename)) end def read_image_with_timeout time_limit = 5 Timeout.timeout(time_limit){ fetch } end end end
class AddTimestampsToUserDetail < ActiveRecord::Migration[5.0] def change add_column :user_details, :created_at, :datetime add_column :user_details, :updated_at, :datetime end end
module SageOne class Client module LedgerAccounts # @example Get all ledger accounts # SageOne.ledger_accounts def ledger_accounts(options={}) get("ledger_accounts", options) end end end end
class CreateSubsets < ActiveRecord::Migration def change create_table :subsets do |t| t.integer :swimset_id t.integer :distance t.integer :stroke_id t.text :comment t.timestamps end end end
require('minitest/autorun') require('minitest/rg') require_relative('../testing_task_2') class TestCardGame < Minitest::Test def setup @card1 = Card.new("Ace", 1) @card2 = Card.new("King", 13) @card3 = Card.new("Queen", 12) @card4 = Card.new("Jack", 11) @card5 = Card.new("Ten", 10) @card6 = Card.new("Nine", 9) @card7 = Card.new("Eight", 8) @cards = [@card1, @card2, @card3, @card4, @card5, @card6, @card7] end def test_card_has_suit() assert_equal("Ace", @card1.suit) end def test_card_has_value() assert_equal(8, @card7.value) end # def test_card_check_for_ace__true() result = CardGame.checkforAce(@card1) assert_equal(true, result) end # def test_card_check_for_ace__false() result = CardGame.checkforAce(@card2) assert_equal(false, result) end # def test_highest_card__firstcard() result = CardGame.highest_card(@card4, @card6) assert_equal(@card4, result) end # def test_highest_card__secondcard() result = CardGame.highest_card(@card7, @card6) assert_equal(@card6, result) end # def test_cards_total() result = CardGame.cards_total(@cards) assert_equal("You have a total of 64", result) end end
class NotifyByDefaultOnBudgets < ActiveRecord::Migration[5.1] class Budget < ApplicationRecord; end def change change_column :budgets, :notify_on_balance_updates, :boolean, :default => true Budget.all.each do |budget| budget.update_attributes!(notify_on_balance_updates: true) end end end
class Weekend < ApplicationRecord self.primary_key = :uuid include HasUuid STATUS = [ "draft", "moderation_pending", "published" ].freeze belongs_to :front_user, optional: true validates :city, presence: true validates :body, length: { in: 20..65_535 } validates :status, inclusion: { in: STATUS }, length: { maximum: 32 } scope :order_by_recent, -> { order("created_at desc") } scope :published, -> { where(status: "published") } before_validation :init_city, on: :create before_validation :init_status, on: :create def init_city self.city ||= "Berlin" end def init_status self.status ||= "draft" end def published? status == "published" end end
require "test_helper" class CompletedTransactionPresenterTest < ActiveSupport::TestCase def subject(content_item) CompletedTransactionPresenter.new(content_item.deep_stringify_keys!) end test "#promotion" do assert_equal "organ-donation", subject(details: { promotion: "organ-donation" }).promotion end end
class RemoveFolderIdColumnFromActiveStorage < ActiveRecord::Migration[6.0] def change remove_column :active_storage_attachments, :folder_id, :integer end end
module Natives class HostDetection class PackageProvider COMMANDS = { 'aix' => 'installp', 'yum' => 'yum', 'packman' => 'packman', 'apt' => 'apt-get', 'feebsd' => 'pkg_add', 'portage' => 'emerge', 'homebrew' => 'brew', 'macports' => 'port', 'solaris' => 'pkg_add', 'ips' => 'pkg', 'zypper' => 'zypper', 'smartos' => 'pkgin' }.freeze PROVIDERS = { 'aix' => 'aix', 'amazon' => 'yum', 'arch' => 'pacman', 'centos' => 'yum', 'debian' => 'apt', 'fedora' => 'yum', 'freebsd' => 'freebsd', 'gcel' => 'apt', 'gentoo' => 'portage', 'linaro' => 'apt', 'linuxmint' => 'apt', 'mac_os_x' => ['homebrew', 'macports'], 'mac_os_x_server' => 'macports', 'nexentacore' => 'solaris', 'omnios' => 'ips', 'openindiana' => 'ips', 'opensolaris' => 'ips', 'opensuse' => 'zypper', 'oracle' => 'yum', 'raspbian' => 'apt', 'redhat' => 'yum', 'scientific' => 'yum', 'smartos' => 'smartos', 'solaris2' => 'ips', 'suse' => 'zypper', 'ubuntu' => 'apt', 'xcp' => 'yum', 'xenserver' => 'yum' }.freeze def initialize(platform) @platform = platform end def name providers = Array(PROVIDERS[@platform.name]) return providers.first if providers.count < 2 providers.find do |provider| which(COMMANDS[provider]) != nil end end protected # copied from Chef cookbook 'apt' # source: apt/libraries/helpers.rb def which(cmd) paths = ( ENV['PATH'].split(::File::PATH_SEPARATOR) + %w(/bin /usr/bin /sbin /usr/sbin /opt/local/bin) ) paths.each do |path| possible = File.join(path, cmd) return possible if File.executable?(possible) end nil end end end end
require 'spec_helper' module Makeloc describe DoGenerator do # loaded once at beginning let!(:ref_hash_with_root) { YAML.load(File.read(REF_LANG_FP)) } let!(:ref_hash) { ref_hash_with_root[REF_LANG] } let!(:incomplete_target_hash_with_root) { YAML.load(File.read(TARGET_INCOMPLETE_ORIGINAL_FP)) } let!(:incomplete_target_hash) { incomplete_target_hash_with_root[TARGET_LANG] } EXTRA_KEYS = %w{ date.extra_key_1 date.formats.extra_key_2 date.extra_key_0.extra_key_00.extra_key_000 date.extra_key_0.extra_key_00.extra_key_001} MISSING_KEYS = %w{ datetime.distance_in_words.about_x_hours.other date.abbr_day_names } # loaded at runtime after each generation let(:target_hash_with_root) { YAML.load(File.read(TARGET_LANG_FP)) } let(:target_hash) { target_hash_with_root[TARGET_LANG] } shared_examples "a brand new generated locale file" do it "should generate a #{TARGET_LANG_FP.basename} file in the same dir" do File.exists? TARGET_LANG_FP end it "#{TARGET_LANG_FP.basename} hash has '#{TARGET_LANG}' as root key" do target_hash_with_root.keys.should ==([TARGET_LANG]) end end shared_examples "a new generated locale file with identical structure" do it "#{TARGET_LANG_FP.basename} hash has identical keys set as #{REF_LANG_FP.basename} hash" do target_hash.flatten_keys.should eql(ref_hash.flatten_keys) end end with_input "y\n" do context "when #{TARGET_LANG_FP.basename} doesn't exist" do with_args "en", REF_LANG_FP before(:each) do FileUtils.rm_rf TARGET_LANG_FP subject.should generate end it_should_behave_like "a brand new generated locale file" it_should_behave_like "a new generated locale file with identical structure" it "gets created with nil leaves" do all_values = [] target_hash.parse_leaves{|k,v| all_values << v } all_values.compact.should be_empty end end context "when #{TARGET_LANG_FP.basename} already exists with some missing keys (ie.: #{MISSING_KEYS.join(', ')}) and some extra keys (ie.: #{EXTRA_KEYS.join(', ')})" do with_args "en", REF_LANG_FP before(:each) do FileUtils.cp TARGET_INCOMPLETE_ORIGINAL_FP, TARGET_LANG_FP subject.should generate end it_should_behave_like "a brand new generated locale file" MISSING_KEYS.each do |key| it "value at '#{key}' is nil" do target_hash.at(key).should be_nil end end it "keeps old values (value at 'date.abbr_month_names' is in lang #{TARGET_LANG})" do target_hash.at('date.abbr_month_names').should ==(incomplete_target_hash.at('date.abbr_month_names')) end EXTRA_KEYS.each do |key| it "keeps extra key #{key} along with its original value" do target_hash.at(key).should == incomplete_target_hash.at(key) end end context "with option --strict" do with_args "en", REF_LANG_FP, '--strict' it_should_behave_like "a new generated locale file with identical structure" end end end end end
class SendParticipantToVoicemail def initialize(participant:, user:) @participant = participant @user = user end def call voicemail_call = create_call ConnectCallToVoicemail.new(incoming_call: voicemail_call).call end private attr_reader :participant, :user def create_call IncomingCall.create(user: user).tap do |call| call.transition_to(:no_answer) call.add_participant(phone_number: participant.phone_number, sid: participant.sid) end end end
require_relative "DNAsequence.rb" class DNAhash attr_reader :hash #******************* #Initialization of a DNA hash #******************* #3 modes: from a DNA sequence, from a string or from a well-formatted hash def initialize(intro, k = 1) if intro.is_a? Hash @hash = intro elsif intro.is_a? DNAsequence #A sequence has been introduced @hash = _seq2hash(intro, k) elsif intro.is_a? String #A simple string of A,C,G,T has been introduced @hash = _seq2hash(DNAsequence.new(intro), k) else puts "Wrong initialization of DNAhash" end #Define other properties @kmerlength = k end #******************* #Easy way to read the hash #******************* def to_s str = '' @hash.each{ |kmer, data| str += "#{kmer} appears #{data[0]} times at #{data[1]}\n" } return str end #******************* #Add the iterator character #******************* def each(&block) @hash.each(&block) self end #******************* #Return the k-mers that are repeated at least t times in at least one window of l nucleotides in the DNA sequence # k, l (length of clump), t (times) => hash(DNAnum/str => [Clump begin1, Clump begin2...]) # O(|chunk|^2 + |chunk| * t) ~ O(|chunk|^2) #******************* def whereareClumps?(l, t) clumps = {} @hash.each{ |kmer, obj| if obj[0] >= t #If the kmer appears at least t times 0.upto(obj[1].length - t){ |i| #Look for t appearances in less than l nucleotides if obj[1][i + t - 1] - obj[1][i] <= l - @kmerlength clumps[kmer] = [] if !clumps.key?(kmer) clumps[kmer].push(obj[1][i]) #Store the position where the clump begins end } end } return clumps end #******************* #Return the frequency of every k-mer in the hash up to mis mismatches. #If the rC = true, the sum of the frequencies of the kmer and the reverse Complement is returned # int => array{int} (where positions codify kmers) # O(4 * length^2 * 3^(length - d)) ????? #******************* def frequencies(mis = 0, rc = false) #Prepare the counters hash freqs = [] 0.upto(Base::NUM_TYPES ** @kmerlength - 1){ |i| freqs[i] = 0 } #Compute the frequences of the simple kmers @hash.each{ |kmer, obj| DNAsequence.new(kmer, @kmerlength).neighbours(mis).each{ |neigh| freqs[neigh.number] += obj[0] } } #Sum the frequences of the reverse complements if the option is selected if rc tmp = [] 0.upto(freqs.length - 1){ |i| rev = DNAsequence.new(i, @kmerlength).rC.number tmp[i] = freqs[i] + freqs[rev] } freqs = tmp end return freqs end #******************* #Return the frequency of the most frequent k-mers in the hash up to mis mismatches # int => hash{string => int} # O(4 * length^2 * 3^(length - d)) ????? #******************* def max(mis = 0, rc = false) freqs = frequencies(mis, rc) #Compute frequencies #Select the most frequent max = 0 mostF = {} 0.upto(freqs.length - 1){ |i| if freqs[i] > max max = freqs[i] mostF = {} end mostF[i] = freqs[i] if freqs[i] >= max } return mostF end #******************* #******************* # #Private methods # #******************* #******************* private #Converts a DNA sequence in a DNA hash formed by k-mers instances # DNAsequence, int [,string] => hash # O(|seq| * |hash|) ~ O(|seq|^2) def _seq2hash(seq, k) dnahash = {} 0.upto(seq.length - k){ |i| kmer = seq.cut(i, k).number dnahash[kmer] = [0, []] if !dnahash.key?(kmer) dnahash[kmer][0] += 1 #Add 1 to the counter for the kmer dnahash[kmer][1].push(i) # Add the position of the kmer } return dnahash end end
require_relative './../../spec_helper' describe ArangoGraph do context "#new" do it "create a new Graph instance without global" do myGraph = ArangoGraph.new graph: "MyGraph", database: "MyDatabase" expect(myGraph.graph).to eq "MyGraph" end it "create a new instance with global" do myGraph = ArangoGraph.new expect(myGraph.graph).to eq "MyGraph" end end context "#create" do it "create new graph" do @myGraph.destroy myGraph = @myGraph.create expect(myGraph.graph).to eq "MyGraph" end end context "#info" do it "info graph" do myGraph = @myGraph.retrieve expect(myGraph.graph).to eq "MyGraph" end end context "#manageVertexCollections" do it "add VertexCollection" do @myGraph.removeEdgeCollection collection: "MyEdgeCollection" @myGraph.removeVertexCollection collection: "MyCollection" myGraph = @myGraph.addVertexCollection collection: "MyCollection" expect(myGraph.orphanCollections[0]).to eq "MyCollection" end it "retrieve VertexCollection" do myGraph = @myGraph.vertexCollections expect(myGraph[0].collection).to eq "MyCollection" end it "remove VertexCollection" do myGraph = @myGraph.removeVertexCollection collection: "MyCollection" expect(myGraph.orphanCollections[0]).to eq nil end end context "#manageEdgeCollections" do it "add EdgeCollection" do myGraph = @myGraph.addEdgeCollection collection: "MyEdgeCollection", from: "MyCollection", to: @myCollectionB expect(myGraph.edgeDefinitions[0]["from"][0]).to eq "MyCollection" end it "retrieve EdgeCollection" do myGraph = @myGraph.edgeCollections expect(myGraph[0].collection).to eq "MyEdgeCollection" end it "replace EdgeCollection" do myGraph = @myGraph.replaceEdgeCollection collection: @myEdgeCollection, from: "MyCollection", to: "MyCollection" expect(myGraph.edgeDefinitions[0]["to"][0]).to eq "MyCollection" end it "remove EdgeCollection" do myGraph = @myGraph.removeEdgeCollection collection: "MyEdgeCollection" expect(myGraph.edgeDefinitions[0]).to eq nil end end context "#destroy" do it "delete graph" do myGraph = @myGraph.destroy expect(myGraph).to be true end end end
module Roby module Queries # Matcher for CodeError exceptions # # In addition to the LocalizedError properties, it allows to match # properties on the Ruby exception that has been thrown class CodeErrorMatcher < LocalizedErrorMatcher attr_reader :ruby_exception_class def initialize super @ruby_exception_class = ::Exception with_model(CodeError) end # Match the underlying ruby exception # # @param [#===,Class] matcher an object that can match an Exception # object, usually an exception class def with_ruby_exception(matcher) with_original_exception(matcher) @ruby_exception_class = matcher self end # Match a CodeError without an original exception def without_ruby_exception with_ruby_exception(nil) end def ===(error) return false if !super ruby_exception_class === error.error end def to_s description = super if ruby_exception_class description.concat(".with_ruby_exception(#{ruby_exception_class})") else description.concat(".without_ruby_exception") end end def describe_failed_match(exception) if description = super return description elsif !(ruby_exception_class === exception.error) if ruby_exception_class return "the underlying exception #{exception.error} does not match the expected #{ruby_exception_class}" else return "there is an underlying exception (#{exception.error}) but the matcher expected none" end end end end end end
def zip(arr1, arr2) result = [] arr1.size.times do |i| result << [arr1[i], arr2[i]] end result end p zip([1, 2, 3], [4, 5, 6]) == [[1, 4], [2, 5], [3, 6]] # ---- With each_with_object ---- def zipp(arr1, arr2) arr1.each_with_object([]).with_index do |(_, result), idx| result << [arr1[idx], arr2[idx]] end end p zipp([1, 2, 3], [4, 5, 6]) == [[1, 4], [2, 5], [3, 6]]
require 'station' describe Station do subject(:mudchute) {described_class.new(:station, :zone_num)} it "A station has a name" do expect(subject.station_name).to eq :station end it "A station has a zone" do expect(subject.zone).to eq :zone_num end end
class Category < ApplicationRecord has_many :category_answers has_many :questions end
# Copyright © 2011-2019 MUSC Foundation for Research Development # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. require 'rails_helper' RSpec.describe "User submitting a ServiceRequest", js: true do def click_add_service_for(service) page.find("button[data-id='#{service.id}']").click wait_for_javascript_to_finish end let!(:user) do create(:identity, last_name: "Doe", first_name: "John", ldap_uid: "johnd", email: "johnd@musc.edu", password: "p4ssword", password_confirmation: "p4ssword", approved: true) end stub_config("system_satisfaction_survey", true) it "is happy" do allow_any_instance_of(Protocol).to receive(:rmid_server_status).and_return(false) ####################################### # Organization structure and Services # ####################################### institution = create(:organization, type: 'Institution', name: 'Institution', abbreviation: 'Instant') provider_non_split = create(:organization, :with_pricing_setup, type: 'Provider', name: 'Provider Non Split', abbreviation: 'Prov No Splt', parent: institution) provider_split = create(:organization, :with_pricing_setup, type: 'Provider', name: 'Provider Split', abbreviation: 'Prov Splt', process_ssrs: true, parent: institution) program_non_split = create(:organization, type: 'Program', name: 'Program Non Split', abbreviation: 'Prog No Splt', parent: provider_split) program_split = create(:organization, type: 'Program', name: 'Program Split', abbreviation: 'Prog Splt', process_ssrs: true, parent: provider_non_split) core1 = create(:organization, type: 'Core', name: 'Core 1', abbreviation: 'Core1', parent: program_split) core2 = create(:organization, type: 'Core', name: 'Core 2', abbreviation: 'Core2', parent: program_non_split) otf_service_core_1 = create(:one_time_fee_service, :with_pricing_map, name: 'Otf Service Core 1', abbreviation: 'Otf Serv Core1', organization: core1) pppv_service_core_1 = create(:per_patient_per_visit_service, :with_pricing_map, name: 'PPPV Service Core 1', abbreviation: 'PPPV Serv Core1', organization: core1) otf_service_core_2 = create(:one_time_fee_service, :with_pricing_map, name: 'Otf Service Core 2', abbreviation: 'Otf Serv Core2', organization: core2) pppv_service_core_2 = create(:per_patient_per_visit_service, :with_pricing_map, name: 'PPPV Service Core 1', abbreviation: 'PPPV Serv Core1', organization: core2) #################### # Survey structure # #################### survey = create(:system_survey, :active, title: 'System Satisfaction Survey', access_code: 'system-satisfaction-survey', active: true) section = create(:section, survey: survey) question_1 = create(:question, question_type: 'likert', content: '1) How satisfied are you with using SPARCRequest today?', section: section) option_1 = create(:option, content: 'Very Dissatisfied', question: question_1) option_2 = create(:option, content: 'Dissatisfied', question: question_1) option_3 = create(:option, content: 'Neutral', question: question_1) option_4 = create(:option, content: 'Satisfied', question: question_1) option_5 = create(:option, content: 'Very Satisfied', question: question_1) question_2 = create(:question, question_type: 'textarea', content: '2) Please leave your feedback and/or suggestions for future improvement.', section: section) ########## # Step 1 # ########## visit root_path wait_for_javascript_to_finish expect(page).to have_selector('.step-header', text: 'STEP 1') ########## # Log in # ########## click_link 'Login / Sign Up' wait_for_javascript_to_finish expect(page).to have_selector("a", text: /Outside User Login/) find("a", text: /Outside User Login/).click wait_for_javascript_to_finish fill_in "Login", with: "johnd" fill_in "Password", with: "p4ssword" click_button 'Login' wait_for_javascript_to_finish ####################### # Add Core 1 Services # ####################### expect(page).to have_selector("span", text: provider_non_split.name) find("span", text: provider_non_split.name).click wait_for_javascript_to_finish find("span", text: program_split.name).click wait_for_javascript_to_finish find("span", text: core1.name).click wait_for_javascript_to_finish expect(page).to have_selector('.core-accordion .service', text: otf_service_core_1.name, visible: true) expect(page).to have_selector('.core-accordion .service', text: pppv_service_core_1.name, visible: true) click_add_service_for(otf_service_core_1) find("a", text: /Yes/).click wait_for_javascript_to_finish within(".shopping-cart") do expect(page).to have_selector('.service', text: otf_service_core_1.abbreviation, visible: true) end click_add_service_for(pppv_service_core_1) within(".shopping-cart") do expect(page).to have_selector('.service', text: pppv_service_core_1.abbreviation, visible: true) end ####################### # Add Core 2 Services # ####################### expect(page).to have_selector("span", text: provider_split.name) find("span", text: provider_split.name).click wait_for_javascript_to_finish find("span", text: program_non_split.name).click wait_for_javascript_to_finish find("span", text: core2.name).click wait_for_javascript_to_finish expect(page).to have_selector('.core-accordion .service', text: otf_service_core_2.name, visible: true) expect(page).to have_selector('.core-accordion .service', text: pppv_service_core_2.name, visible: true) click_add_service_for(otf_service_core_2) within(".shopping-cart") do expect(page).to have_selector('.service', text: otf_service_core_2.abbreviation, visible: true) end click_add_service_for(pppv_service_core_2) within(".shopping-cart") do expect(page).to have_selector('.service', text: pppv_service_core_2.abbreviation, visible: true) end click_link 'Continue' wait_for_javascript_to_finish ########## # Step 2 # ########## expect(page).to have_selector('.step-header', text: 'STEP 2') click_link("New Project") wait_for_javascript_to_finish fill_in("Short Title:", with: "My Protocol") fill_in("Project Title:", with: "My Protocol is Very Important - #12345") click_button("Select a Funding Status") find("li", text: "Funded").click expect(page).to have_button("Select a Funding Source") click_button("Select a Funding Source") find("li", text: "Federal").click fill_in "Primary PI:", with: "john" expect(page).to have_selector("div.tt-selectable", text: /johnd@musc.edu/) first("div.tt-selectable", text: /johnd@musc.edu/).click wait_for_javascript_to_finish click_button 'Save' wait_for_page(protocol_service_request_path) click_link 'Save and Continue' wait_for_javascript_to_finish ########## # Step 3 # ########## expect(page).to have_selector('.step-header', text: 'STEP 3') find('#project_start_date').click within(".bootstrap-datetimepicker-widget") do first("td.day", text: "1").click end find('#project_end_date').click within(".bootstrap-datetimepicker-widget") do first("td.day", text: "1").click end click_link 'Save and Continue' wait_for_javascript_to_finish ########## # Step 4 # ########## expect(page).to have_selector('.step-header', text: 'STEP 4') find("a", text: "(?)").click wait_for_javascript_to_finish fill_in 'visit_group_day', with: 1 click_button 'Save changes' wait_for_javascript_to_finish click_link 'Save and Continue' wait_for_javascript_to_finish ########## # Step 5 # ########## expect(page).to have_selector('.step-header', text: 'STEP 5') click_link 'Save and Continue' wait_for_javascript_to_finish ########## # Step 6 # ########## expect(page).to have_selector('.step-header', text: 'STEP 6') click_link 'Submit Request' wait_for_javascript_to_finish ########## # Survey # ########## within '.modal-dialog' do find('.yes-button').click wait_for_javascript_to_finish find('#response_question_responses_attributes_0_content_very_satisfied').click fill_in 'response_question_responses_attributes_1_content', with: 'I\'m so happy!' click_button 'Submit' wait_for_javascript_to_finish end ########## # Step 5 # ########## expect(page).to have_selector('.step-header', text: 'Confirmation') click_link 'Go to Dashboard' wait_for_javascript_to_finish ############# # Dashboard # ############# expect(page).to have_content("My Protocol") end end