text
stringlengths
10
2.61M
class NewWorkoutCell < UICollectionViewCell attr_reader :reused attr_accessor :custom_delegate def rmq_build rmq(self).apply_style :new_workout_cell q = rmq(self.contentView) self.contentView.styleClass = 'new_workout_cell' @exercise_label = q.append(UILabel, :exercise_label).get end def prepareForReuse @reused = true end def update(setGroup) # Cleanup rmq(self.contentView).find(:work_set_view).remove @exercise_label.text = setGroup[:exercise][:name] @edit_button = rmq(self.contentView).append(UIButton, :edit_button) @edit_button.on(:tap) do |sender, event| @custom_delegate.edit_set_group(setGroup) end setGroup[:worksets].each_with_index do |workset, index| ws_view = rmq(self.contentView).append(WorkSetView).get ws_view.workset = workset ws_view.layout_views rmq(ws_view).frame = {l: (60 * index) + 10, t: 45, w: 50, h: 85} rmq(ws_view).on(:tap) do |sender, event| if workset[:accomplished_reps] == 0 workset[:accomplished_reps] = workset[:prescribed_reps] else workset[:accomplished_reps] = workset[:accomplished_reps] - 1 end ws_view.layout_views end end end end
require 'soar_customer' require 'jsender' require 'lib/web/support/logging' require_relative 'model_factory' module SoarSc module Web module Models class Customer include Jsender attr_reader :configuration attr_accessor :data_provider class SoarCustomerDaasError < StandardError; end def initialize(configuration) @configuration = configuration validate_configuration factory = SoarSc::Web::Models::ModelFactory.new(@configuration) @data_provider = factory.create authenticate end def create_profile(customer_info) @data_provider.create_profile(customer_info) rescue => e Logger.log.debug "Failed to create profile: #{e.message}" fail 'Exception while trying to create profile' end protected def authenticate credential = { 'username' => configuration['username'], 'password' => configuration['password'] } @data_provider.authenticate(credential) end private def validate_configuration raise SoarCustomerDaasError.new('No configuration') if @configuration.nil? || @configuration.empty? raise SoarCustomerDaasError.new('Missing username') if @configuration['username'].nil? || @configuration['username'].empty? raise SoarCustomerDaasError.new('Missing password') if @configuration['password'].nil? || @configuration['password'].empty? raise SoarCustomerDaasError.new('Missing server url') if @configuration['server_url'].nil? || @configuration['server_url'].empty? raise SoarCustomerDaasError.new('Missing adaptor') if @configuration['adaptor'].nil? || @configuration['adaptor'].empty? end end end end end
require 'test_helper' class KeywordTest < ActiveSupport::TestCase setup do @keyword = keywords(:keyword1) @amazon = YAML.load(open('test/fixtures/amazon.txt').read) @rakuten_books = YAML.load(open('test/fixtures/rakuten_books.txt').read) @product = products(:keyword_search1) Product.all.each(&:save) end test "Amazonで検索後結果を保存して返す" do pages = 0 products = [] assert_difference 'Product.count', @amazon.last.size do AmazonEcs.stub(:search, @amazon) do pages, products = @keyword.amazon_search end end assert_equal @amazon.first, pages assert_equal @amazon.last.size, products.size end test "楽天ブックスで検索後結果を保存して返す" do pages = 0 products = [] assert_difference 'Product.count', @rakuten_books.last.size do RakutenBooks.stub(:search, @rakuten_books) do pages, products = @keyword.rakuten_search end end assert_equal @rakuten_books.first, pages assert_equal @rakuten_books.last.size, products.size end test "groongaで検索後結果を返す" do pages = 0 products = [] assert_no_difference 'Product.count' do pages, products = @keyword.search end assert_equal 1, pages assert_equal @product, products.first end test "新規保存時にはAmazon検索後Groongaで検索実行、keyword_productsを保存" do value = 'new keyword' category = 'books' keyword = Keyword.new(:value => value, :category => category) assert_difference 'Product.count', @amazon.last.size do assert_difference 'KeywordProduct.count', @amazon.last.size do AmazonEcs.stub(:search, @amazon) do keyword.save end end end end end
require 'test_helper' class ArrayTest < ActiveSupport::TestCase context '#to_xml method' do setup do @version = Gem::Version.new(RUBY_VERSION) @ruby_24 = Gem::Version.new('2.4.0') end should 'not add the attr params as default' do xml = Nokogiri::XML::Document.parse([1,2].to_xml) if @version < @ruby_24 assert xml.xpath("//fixnums[@type]").empty? else assert xml.xpath("//integers[@type]").empty? end end should 'not add the attr params if skip_types => true is passed' do xml = Nokogiri::XML::Document.parse([1,2].to_xml(:skip_types => true)) if @version < @ruby_24 assert xml.xpath("//fixnums[@type]").empty? else assert xml.xpath("//integers[@type]").empty? end end should 'add the attr params if skip_types => false is passed' do xml = Nokogiri::XML::Document.parse([1,2].to_xml(:skip_types => false)) if @version < @ruby_24 assert !xml.xpath("//fixnums[@type]").empty? else assert !xml.xpath("//integers[@type]").empty? end end end end
require_relative 'linked_list' def create_new_list #tests creating a new list list = LinkedList.new() end def test_push #test pushing nodes onto list list = LinkedList.new() list.push("Mask") list.push("Majora's") list.push("Zelda") list.push("Legend") list.push("The") puts list.to_s unless list.length != 5 puts "push test passed" else puts "push test failed, length is " + list.length.to_s end end def test_pop #test poping elements off of the top of the list list = LinkedList.new() i = 1 while i <= 10 list.push(i) i+=1 end i = 1 until i > 5 list.pop i+=1 end #puts list.to_s unless list.length != 5 puts "pop test passed" else puts "pop test failed, length is " + list.length.to_s end end def test_append list = LinkedList.new() i = 0 until i == 10 list.append(i) puts list.to_s i += 1 end unless list.length != 10 puts "append test passed" else puts "append test failed, length is" + list.length.to_s end end def main test_pop test_push test_append end main
module LayoutHelper def title title = '' title << "#@title - " if @title title << @cobrand.name if @cobrand title << " (#{Rails.env.last(3).upcase})" unless production? title end def body_class classes = [page_type] classes << 'ros' if params[:partner_style] == 'ros' classes.join ' ' end def block_to_partial(partial_name, options = {}, &block) # http://www.igvita.com/2007/03/15/block-helpers-and-dry-views-in-rails/ # 1. Capture is a Rails helper which will 'capture' the output of a block into a variable # 2. Merge the 'body' variable into our options hash # 3. Render the partial with the given options hash. Just like calling the partial directly. options.merge!(:body => capture(&block)) concat render(:partial => partial_name, :locals => options) end # creates a standard global layout for wrapping page layouts def page(&block) @page ||= {} block_to_partial('layouts/global', &block) end # sets a class for the body tag # default is full page. other values are popup, interruptus # override for a specific view by setting @page[:type] def page_type if @page[:type] raise ArgumentError, 'page type must be full, popup, or interruptus' unless ['full','popup', 'interruptus'].include? @page[:type] end return @page[:type] || 'full' end # sets a class on the first div inside the body tag # override @page[:section] def site_section # this probably needs to be a more complex piece # mapping controllers to site sections # but that feels heavy handed # NMK @page[:section] || 'standard' end # sets id on the first div inside the body # override with @page[:id] def page_id page_id = @page[:id] || @page_id || "#{params[:controller]}_#{params[:action]}" page_id.split("/")[-1] end # sets class on div id=layout # override with @page[:layout] def page_layout @page[:layout] || 'standard' end def talk_bubble(&block) block_to_partial('layouts/containers/talk_bubble', &block) end def popup(&block) @page ||= {} @page[:type] = 'popup' suppress 'pre_header', 'header', 'footer', 'admin' block_to_partial('layouts/global', &block) end def interruptus(&block) @page ||= {} @page[:type] = "interruptus" suppress 'pre_header', 'header', 'footer', 'admin' block_to_partial('layouts/global', &block) end def suppress(*args) @page[:suppress] ||= [] @page[:suppress].push(*args) end def suppressed?(item) @page[:suppress] ||= [] # in case no page[:suppress] define return @page[:suppress].include? item end class UI_Block < BlockHelpers::Base attr_accessor :block_type, :content, :options def initialize(block_type='module', opts={}) @content = {} @options = {:block => opts} classnames = determine_classnames block_type end def display [@options[:header], @options[:content], @options[:footer]].each do | opt | opt[:class] ||= '' opt[:class] << " " unless opts[:class].empty? opt[:class] << 'ui_tab' end block_to_partial "layouts/#{block_type}", @options end def determine_classnames(type) classnames = {:header => {}, :content => {}, :footer => {}} classnames[:header][:class] = %{#{type}_h} classnames[:content][:class] = %{#{type}_c} classnames[:footer][:class] = %{#{type}_f} classnames end end class Block_Header < BlockHelpers::Base def initialize(opts={}) parent.options[:header].merge! opts end def display(body) parent.content[:header] = body end end class Block_Content < BlockHelpers::Base def initialize(opts={}) parent.options[:content].merge! opts end def display(body) parent.content[:content] = body end end class Block_Footer < BlockHelpers::Base def initialize(opts={}) parent.options[:footer].merge! opts end def display(body) parent.content[:footer] = body end end def ui_module(opts={}) ui_block('module', opts) end # The Columns class is transformed into a helper method that creates a column structure. # Its partner class, Column, is used to denote blocks for actual column content. # @param - num_cols - Gives the number of columns intended. Used to track count internally. # @param - options - Column accepts all standard html options, and one special option--*inner* # *inner* simply indicates this set of columns is nested within another. # More in the wiki: http://bugs.hive.viewpoints.com/wiki/viewpoints-site/Column_Helper class Columns < BlockHelpers::Base attr_accessor :num_cols, :col_count, :inner def initialize(num_cols, options={}) @col_count = 0 @num_cols = num_cols @inner = options[:inner] || false classes = "cols cols_#{num_cols.to_s}" classes << " inner" if options[:inner] classes << " #{options[:class]}" if options[:class] options.delete :inner @options = options.merge!({:class => classes}) end def display(body) content_tag :div, @options do body end end # The Column class wraps the passed block in a column structure. # It should always be used within a *columns* block # @param - num - Indicates the position of the column # @param - options - Accepts all standard html options, plus special option *span* # *span* determines the number of columns spanned and affects column count # Note that all of this depends on correct arithmetic & supporting css class Column < BlockHelpers::Base def initialize(num, options={}) parent.col_count += options[:span] || 1 classes = "col col_#{num.to_s}" classes << " span_#{options[:span]}" if options[:span] classes << " inner_col" if parent.inner classes << " first" if num == 1 classes << " last" if parent.col_count == parent.num_cols classes << " #{options[:class]}" if options[:class] options.delete :span @options = options.merge!({:class => classes}) end def display(body) content_tag :div, @options do content_tag :div, :class => 'col_content' do body end end end end end def rounded_box(title, options = {}, &block) # Render partial with the given options and block content block_to_partial('layouts/rounded_box', options.merge(:title => title), &block) end def pagination_panel(pagination_obj, &block) # Renders pagination links & jump to form, as in admin tools block_to_partial('layouts/admin/panel_pagination', :pagination_obj => obj, &block) end # Creates the common rounded tab interface used on product pages, e.g. Does not create tab sheets/pages def ui_tabs(tab_array, id='', active_tab=0) tabs = [] # Rename ul if needed (hilite_tab fn depends on this naming convention) id << '_tabs' if id[-5,-1] != '_tabs' tab_array.each_with_index do | tab, i | active = (tab == active_tab || i == active_tab) ? 'active' : '' tabs << content_tag(:li, link_to_function(tab.humanize.titleize, "hilite_tab('#{tab}')"), {:id => "#{tab}_tab", :class => active}) end content_tag(:ul, tabs.join("\n\t"), {:class => 'tabs', :id => id}) end # Creates a tab link element for use in VP standard tabbed interface # Option - data-true_link - true|false - Prevent javascript show/hide initialization. Treats tab as a true link. def ui_tab(url, text, opts={}) opts["class"] ||= '' opts["class"] << " " unless opts["class"].empty? opts["class"] << 'ui_tab' opts[:id] ||= 'needs_id' opts[:id] += "_tab" unless opts[:id][-4, -1] == "_tab" content_tag :li, opts do rounded_corner_image_tag("tl") << link_to(text, url) << rounded_corner_image_tag('tr') end end def dev_comment(comment) # comments displayed in html source in development only # for embedding information about page structure, for instance App.development? ? comment : "" end # Button Helper, v2.7 # http://bugs.hive.viewpoints.com/wiki/viewpoints-site/Button_Helper def button(title, values = {}, div_it=true) # Setting defaults values[:type] ||= "button" values[:category] ||= "primary" # Setting inline img icon if category string matches inline_icon = "" if values[:category]=~ /secure|prev|next/ inline_icon = image_tag("buttons_#{$&}.gif") end # Setting onclick depending on URL endcap = content_tag(:div, '&nbsp;', :class => 'endcap') # Generating content tag # NMK - should probably check for :id, otherwise emits id="_container" full_button = content_tag(:div, :id => "button_#{values[:id]}container", :class => "button button_" + values[:category]) do content_tag(:input, inline_icon, :value => title, :onmouseover => "$(this).up().addClassName('button_#{values[:category]}-hilited')", :onmouseout => "$(this).up().removeClassName('button_#{values[:category]}-hilited')", :style => "margin:0;#{values[:style]}", :type => values[:type], :onclick => build_click_action(values), :name => values[:name], :class => values[:class], :id => values[:id], :disabled => values[:disabled], :rel => values[:rel], :title => values[:title], :tabindex => values[:tabindex], :target => values[:target] ).sub("></input>", " />") + endcap end if values[:center] then if values[:width] content_tag(:div, full_button, :class => "center_buttons", :style => "width:#{values[:width]}px") else content_tag(:div, full_button, :class => "center_buttons") end else full_button end end # Creates a sortable element (<li> by default) def sortable_item(id='', markup='', el='li') content_tag el, :id => id, :class => 'sortable' do markup end end def build_click_action(values) # onclick wins in every case, if you provided it you win! # if you provided confirm, it'll be injected... if !values[:onclick] and values[:url] values[:onclick] = "window.location='#{url_for values[:url]}'" end values[:confirm].blank? ? values[:onclick] : "if (confirm('#{values[:confirm]}'))\{#{values[:onclick]}\}" end def bar_delimiter return ' <span class="bar_delimiter">|</span> ' end # a simple hook for including cobrand javascript # if a file called 'cobrand.js' exists in a cobrand's /public/javascript directory # this will emit a script tag. # if not, just exits. def cobrand_javascript_include_tag path = "#{Rails.root}/cobrands/#{@cobrand.short_name}/public/javascripts/cobrand.js" if File.exists? path return javascript_include_tag "/#{@cobrand.short_name}/javascripts/cobrand.js" end end # Returns markup for a complete table # @param - headings - an array of table headings # @param - data - an array of content for column data # @param - options - standard html options hash, with special options: # - col_classes - an array of classes to be applied respectively to columns # if omitted, these classes are derived from heading names # TODO | Put content array in block? More natural syntax during use. class Auto_Table < BlockHelpers::Base attr_accessor :count_cols, :count_rows def initialize(headings=[], data=[], options={}) @count_cols = headings.length @count_rows = data.length @options = options @col_classes = options.delete(:col_classes) || write_column_classes(headings) @text_on_empty = options.delete(:text_on_empty) || 'No results' @table_head = %{<thead>\n\t#{th_row(headings)}</thead>\n} @table_body = %{<tbody>\n\t#{table_data(data)}</tbody>\n} end def display(body='') content_tag :table, @options do @table_head << @table_body end end def write_column_classes(headings_array) headings_array.map do | text | strip_tags(text.to_s).gsub(/[^a-zA-Z0-9\- ]/, '').gsub(/ /, '_').underscore.chomp('_') end end def th_row(headings_array) table_row headings_array, 'th' end def options_with_helper_classes(opts, n, td_or_th) extra_classes = [] extra_classes << "first" if n == 0 extra_classes << "last" if n == @count_cols - 1 extra_classes << (n % 2 == 0 ? "odd" : "even") extra_classes << %{#{td_or_th}_#{@col_classes[n]}} if @col_classes[n] extra_classes << %{td_col_#{n+1}} unless extra_classes.empty? opts[:class] ||= '' opts[:class] << ' ' unless opts[:class].empty? opts[:class] << extra_classes.join(' ') end opts end def table_data(data_array, opts={}) # handle empty table data if data_array.empty? @count_rows = 1 return %{<tr>\n\t<td colspan="#{@count_cols}" class="empty">#{@text_on_empty}</td>\n</tr>\n} end data_rows = [] data_array.each do | row_array | data_rows << table_row( row_array ) end data_rows.join("\n") end def table_row(row_array, td_or_th='td') row = [] row_array.each_with_index do | cell_contents, i | cell_contents ||= '' if cell_contents.class == Fixnum || cell_contents.class == Bignum cell_contents = cell_contents.to_s end if cell_contents.class == String opts = options_with_helper_classes( {}, i, td_or_th ) row << content_tag( td_or_th, cell_contents, opts ) # Hashes are transformed into the td element itself # This allows for special cases where a td needs custom classes, etc. # :content is td content elsif cell_contents.class == Hash opts = cell_contents[:options] || {} opts = options_with_helper_classes( opts, i, td_or_th ) text = cell_contents.delete(:content) || '' row << (content_tag td_or_th, opts do text end) end end # Handle missing data cols if row.length < (@count_cols - 1) row << %{<td colspan="#{@count_cols - row_array.length}"></td>} end return "<tr>\n\t" << row.join( "\n\t" ) << "</tr>\n" end end end
# frozen_string_literal: true require 'rake/testtask' require 'fileutils' Rake::TestTask.new do |t| t.libs << 'lib' << 'test' t.test_files = FileList['test/*_test.rb'] t.verbose = true t.warning = false end desc Rake::Task['test'].comment task :default => :test
#GET request get '/sample-44-how-to-assemble-document-and-add-multiple-signatures-and-signers-to-a-document' do haml :sample44 end #POST request post '/sample-44-how-to-assemble-document-and-add-multiple-signatures-and-signers-to-a-document' do #Set variables set :client_id, params[:clientId] set :private_key, params[:privateKey] set :file_id, params[:fileId] set :first_name, params[:firstName] set :last_name, params[:lastName] set :first_email, params[:firstEmail] set :second_email, params[:secondEmail] set :gender, params[:gender] set :base_path, params[:basePath] #Set download path downloads_path = "#{File.dirname(__FILE__)}/../public/downloads" #Remove all files from download directory or create folder if it not there if File.directory?(downloads_path) Dir.foreach(downloads_path) { |f| fn = File.join(downloads_path, f); File.delete(fn) if f != '.' && f != '..' } else Dir::mkdir(downloads_path) end begin #Check required variables raise 'Please enter all required parameters' if settings.client_id.empty? or settings.private_key.empty? or settings.first_email.empty? or settings.second_email.empty? or settings.first_name.empty? #Prepare base path if settings.base_path.empty? base_path = 'https://api.groupdocs.com' elsif settings.base_path.match('/v2.0') base_path = settings.base_path.split('/v2.0')[0] else base_path = settings.base_path end #Configure your access to API server GroupDocs.configure do |groupdocs| groupdocs.client_id = settings.client_id groupdocs.private_key = settings.private_key #Optionally specify API server and version groupdocs.api_server = base_path # default is 'https://api.groupdocs.com' end (settings.last_name.nil? or settings.last_name.empty?) ? settings.last_name = settings.first_name : settings.last_name second_signer_name = settings.first_name + "2" second_signer_last_name = settings.last_name + "2" #Construct path file_path = "#{Dir.tmpdir}/#{params[:file][:filename]}" #Open file File.open(file_path, 'wb') { |f| f.write(params[:file][:tempfile].read) } # Make a request to API using client_id and private_key file = GroupDocs::Storage::File.upload!(file_path, {}) #Raise exception if something went wrong raise 'No such file' unless file.is_a?(GroupDocs::Storage::File) #Make GroupDocs::Storage::Document instance document = file.to_document #Create datasource with fields datasource = GroupDocs::DataSource.new #Get arry of document's fields enteredData = {"name" => settings.first_name, "gender" => settings.gender} #Create Field instance and fill the fields datasource.fields = enteredData.map { |key, value| GroupDocs::DataSource::Field.new(name: key, type: :text, values: Array.new() << value) } #Adds datasource. datasource.add!() #Creates new job to merge datasource into document. job = document.datasource!(datasource) sleep 10 #Wait for merge and convert #Returns an hash of input and output documents associated to job. document = job.documents!() #Set converted document GUID guid = document[:inputs][0].outputs[0].guid file = GroupDocs::Storage::File.new({:guid => guid}) #Set converted document Name file_name = document[:inputs][0].outputs[0].name #Create envelope using user id and entered by user name envelope = GroupDocs::Signature::Envelope.new envelope.name = file_name envelope.create!({}) #Add uploaded document to envelope envelope.add_document!(file.to_document, {}) #Get role list for current user roles = GroupDocs::Signature::Role.get!({}) #Create new first recipient first_recipient = GroupDocs::Signature::Recipient.new first_recipient.email = settings.first_email first_recipient.first_name = settings.first_name first_recipient.last_name = settings.last_name first_recipient.role_id = roles.detect { |role| role.name == 'Signer' }.id #Create new second recipient second_recipient = GroupDocs::Signature::Recipient.new second_recipient.email = settings.second_email second_recipient.first_name = second_signer_name second_recipient.last_name = second_signer_last_name second_recipient.role_id = roles.detect { |role| role.name == 'Signer' }.id #Add first recipient to envelope first_recipient = envelope.add_recipient!(first_recipient) #Add second recipient to envelope second_recipient = envelope.add_recipient!(second_recipient) #Get document id document = envelope.documents!({}) #Get field and add the location to field field1 = GroupDocs::Signature::Field.get!({}).detect { |f| f.type == :signature } field1.location = {:location_x => 0.15, :location_y => 0.23, :location_w => 150, :location_h => 50, :page => 1} field1.name = 'singlIndex1' #Add field to envelope envelope.add_field!(field1, document[0], first_recipient, {}) #Get field and add the location to field field2 = GroupDocs::Signature::Field.get!({}).detect { |f| f.type == :signature } field2.location = {:location_x => 0.35, :location_y => 0.23, :location_w => 150, :location_h => 50, :page => 1} field2.name = 'singlIndex2' #Add field to envelope envelope.add_field!(field2, document[0], second_recipient, {}) #Send envelop envelope.send!() #Prepare to sign first url first_iframe = "/signature2/signembed/#{envelope.id}/#{first_recipient.id}" #Construct result string first_url = GroupDocs::Api::Request.new(:path => first_iframe).prepare_and_sign_url #Prepare to sign second url second_iframe = "/signature2/signembed/#{envelope.id}/#{second_recipient.id}" #Construct result string second_url = GroupDocs::Api::Request.new(:path => second_iframe).prepare_and_sign_url #Generate iframes URL case base_path when 'https://stage-api-groupdocs.dynabic.com' first_iframe = "https://stage-api-groupdocs.dynabic.com#{first_url}" second_iframe = "https://stage-api-groupdocs.dynabic.com#{second_url}" when 'https://dev-api-groupdocs.dynabic.com' first_iframe = "https://dev-apps.groupdocs.com#{first_url}" second_iframe = "https://dev-apps.groupdocs.com#{second_url}" else first_iframe = "https://apps.groupdocs.com#{first_url}" second_iframe = "https://apps.groupdocs.com#{second_url}" end #Set iframe with document GUID or raise an error if guid #Make first iframe first_iframe = "<p><span style=\"color: green\">Document for first signer</span></p><iframe id='downloadframe' src='#{first_iframe}' width='800' height='1000'></iframe><br>" #Make second iframe second_iframe = "<p><span style=\"color: green\">Document for second signer</span></p><iframe id='downloadframe' src='#{second_iframe}' width='800' height='1000'></iframe>" else raise 'File was not converted' end rescue Exception => e err = e.message end #Set variables for template haml :sample44, :locals => {:userId => settings.client_id, :privateKey => settings.private_key, :first_iframe => first_iframe, :second_iframe => second_iframe, :err => err} end
class Admin::PollsController < Admin::ResourceController model_class Poll def clear_responses if @poll = Poll.find(params[:id]) @poll.clear_responses flash[:notice] = t('polls_controller.responses_cleared', :poll => @poll.title) end redirect_to :action => :index end protected def load_models # Order polls by descending date, then alphabetically by title self.models = model_class.all(:order => Poll.send(:sanitize_sql_array, [ "COALESCE(start_date, ?) DESC, title", Date.new(1900, 1, 1) ])) end end
class Batch def self.generate new id: Guid.generate, uri: Uri.generate, created_at: Time.generate.format, batch_size: Int.generate, persisted_batch_size: Int.generate, account_reference: AccountReference.generate, created_by: String.generate, name: String.generate, status: Status.generate end def initialize(hsh) @hsh = hsh end def to_xml <<EOS <?xml version="1.0" encoding="utf-8"?> <messagebatch id="#{id}" uri="#{uri}" xmlns="http://api.esendex.com/ns/"> <createdat>#{created_at}</createdat> <batchsize>#{batch_size}</batchsize> <persistedbatchsize>#{persisted_batch_size}</persistedbatchsize> #{status.to_xml} <accountreference>#{account_reference}</accountreference> <createdby>#{created_by}</createdby> <name>#{name}</name> </messagebatch> EOS end def method_missing(sym, *args) return @hsh[sym] if @hsh.has_key?(sym) super end end class Status def self.generate new acknowledged: 0, authorisation_failed: 0, connecting: 0, delivered: 0, failed: 0, partially_delivered: 0, rejected: 1, scheduled: 0, sent: 0, submitted: 0, validity_period_expired: 0, cancelled: 0 end def initialize(hsh) @hsh = hsh end # ugh def status :rejected end def to_xml <<EOS <status> <acknowledged>#{acknowledged}</acknowledged> <authorisationfailed>#{authorisation_failed}</authorisationfailed> <connecting>#{connecting}</connecting> <delivered>#{delivered}</delivered> <failed>#{failed}</failed> <partiallydelivered>#{partially_delivered}</partiallydelivered> <rejected>#{rejected}</rejected> <scheduled>#{scheduled}</scheduled> <sent>#{sent}</sent> <submitted>#{submitted}</submitted> <validityperiodexpired>#{validity_period_expired}</validityperiodexpired> <cancelled>#{cancelled}</cancelled> </status> EOS end def method_missing(sym, *args) return @hsh[sym] if @hsh.has_key?(sym) super end end
Rails.application.routes.draw do # homepage ("/") goes to planes controller, index action root to: "planes#index" # CRUD routes for planes resources :planes # get "/planes", to: "planes#index" # post "/planes", to: "planes#create" # get "/planes/new", to: "planes#new" # get "/planes/:id/edit", to: "planes#edit" # get "/planes/:id", to: "planes#show" # put "/planes/:id", to: "planes#update" # delete "/planes/:id", to: "planes#destroy" end
require "yaml" require "ostruct" # Public: The node class. # # A node which describes the data tree behaviour, and all methods # to be called on a data node. Node inherits from (OpenStruct)[http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html] # which is part of Ruby standard library. OpenStruct is like a Struct # where you can also arbitrarily define attributes at runtime. # # Although any type of node is valid, the default types of root, room, # item and player have their own constructors. These have their own # key/value pairs. # # Example: Create the root node and then any number of child nodes. To # recreate the first room of Zork (http://en.wikipedia.org/wiki/Zork) # we could use the following code: # # game = Node.root do # room(:west_of_house) do # player # item(:mailbox, 'mailbox') do # item(:leaflet, 'leaflet', 'small') # end # item(:rubber_mat, 'rubber', 'mat') # end # end class Node < OpenStruct def init_with(c) c.map.keys.each do |k| instance_variable_set("@#{k}", c.map[k]) end @table.keys.each do |k| new_ostruct_member(k) end end def self.save(node, file='save.yaml') File.open(file, 'w+') do |f| f.puts node.to_yaml end end def self.load(file='save.yaml') YAML::load_file(file) end def puts(*s) STDOUT.puts( s.join(' ').word_wrap ) end # Public: Defaults for whether a node type is open or not. # When interacting with the game world, open nodes will show their # contents. If a node is also defined with openable? = true its :open # state can be changed using the ingame open and close commands. DEFAULTS = { :root => { :open => true }, :room => { :open => true }, :item => { :open => false }, :scenery => { :open => false, :fixed => true }, :player => { :open => true } } # Public: Initialize a node # # parent - reference to the new node's parent node. This defaults to # nil if not given. nil should only be used for the root node. # not given. # tag - unique ID (as a symbol) given to the node # defaults - block containing default key/values of the node. # &block - this enables us to define its children. instance_eval is # used instead of yield self, eliminating the need to think # of unique block parameter names. A node can accessed using # `self`. def initialize(parent=nil, tag=nil, defaults={}, &block) super() defaults.each {|k,v| send("#{k}=", v) } self.parent = parent self.parent.children << self unless parent.nil? self.tag = tag self.children = [] instance_eval(&block) unless block.nil? end # Public: *Room* constructor. def room(tag, &block) Node.new(self, tag, DEFAULTS[:room], &block) end # Public: *Item* constructor. def item(tag, name, *words, &block) i = Node.new(self, tag, DEFAULTS[:item]) i.name = name i.words = words i.instance_eval(&block) if block_given? end # Public: *Scenery* constructor # # used for item behaviour without item properties def scenery(tag, name, *words, &block) i = Node.new(self, tag, DEFAULTS[:scenery]) i.name = name i.words = words i.instance_eval(&block) if block_given? end # Public: *Player* constructor. # # Requires: Player < Node to be defined. def player(&block) Player.new(self, :player, DEFAULTS[:player], &block) end # Public: *Root* constructor. def self.root(&block) Node.new(nil, :root, &block) end # Public: Traverses the tree until a room is found. # # This is useful because not all parents of items / player are rooms. # For example an item can be within an item. # # Returns: the room node on the called object. def get_room return self if parent.tag == :root parent.get_room end # Public: Traverses the tree upwards until the root node is found def get_root return self if tag == :root || parent.nil? parent.get_root end # Public: Lists the ancestors of a node. def ancestors(list=[]) return list if parent.nil? list << parent parent.ancestors(list) end # Public: Helper, will return false if described == false or the # key/value isn't defined (nil) on the node. # # Returns true or false def described? if respond_to?(:described) self.described else false end end # Public: Constructs the node's description and outputs it to STDOUT # # Returns description or short description if described? is true. # Returns presence description of children if the node is open. def describe base = "" if !described? && respond_to?(:desc) self.described = true base << desc.to_s elsif described? && respond_to?(:short_desc) base << short_desc.to_s elsif described? && !respond_to?(:short_desc) base << desc.to_s else base << "I see nothing special" end if open && !children.empty? base << "<br>" if parent.tag == :root base << "You also see:" + "<br>" else base << "Inside it you see:" + "<br>" end children.each do |c| base << "#{c.presence}<br>" if c.presence end end puts base end # Public: Evaluates whether a node has a key for it's short description. # # Returns: self.short_desc if defined. Otherwise returns the node's tag # as a String. def short_description if respond_to?(:short_desc) short_desc else tag.to_s end end # Public: returns true if the node is hidden (a child in a closed node). def hidden? return false if parent.tag == :root return true if parent.open == false parent.hidden? end # Public: This looks at the node to see whether there is a script # This returns TRUE if there IS a script. Oddly. # # Returns: # if true - calls the script # if false - returns true def script(key, *args) return true unless respond_to?("script_#{key}") eval(self.public_send("script_#{key}")) end # Public: Moves the position of a Node in the tree from a parent to another # parent. # # Inputs: # thing - Node to be moved # to - target parent Node # check - when false the method skips validating hidden items or whether a # node is open. # # Method calls find to get the object and destination nodes. If the # destination is hidden, or doesn't respond to 'self.open == true' # then the method replies it can't do that. Otherwise the object's parent # child-node reference is deleted, and this is added to the target's children # node. The parent of the object is set as the destination note # # Returns: Modifies the Node tree def move(thing, to, check=true) item = find(thing) dest = find(to) return if item.nil? if check && item.hidden? puts "You can't get to that right now" return end return if dest.nil? if check && (dest.hidden? || dest.open == false) puts "You can't put that there" return end if dest.ancestors.include?(item) puts "Are you trying to destroy the universe?" return end item.parent.children.delete(item) dest.children << item item.parent = dest end # Public: Helper method which evaluates the object and issues the correct # function to find the node described by 'thing' # # Returns Node found in by searching for thing or nil def find(thing) case thing when Symbol find_by_tag(thing) when String find_by_string(thing) when Array find_by_string(thing.join(' ')) when Node thing end end def find_by_tag(tag) return self if self.tag == tag children.each do|c| res = c.find_by_tag(tag) return res unless res.nil? end return nil end def find_by_string(words) words = words.split unless words.is_a?(Array) nodes = find_by_name(words) if nodes.empty? puts "I don't see that here" return nil end # Score the nodes by number of matching adjectives nodes.each do |i| i.search_score = (words & i.words).length end # Sort the score so that highest scores are # at the beginning of the list nodes.sort! do |a,b| b.search_score <=> a.search_score end # Remove any nodes with a search score less # than the score of the first item in the list nodes.delete_if do |i| i.search_score < nodes.first.search_score end # Interpret the results if nodes.length == 1 return nodes.first else puts "Which item do you mean?" nodes.each do |i| puts " * #{i.name} (#{i.words.join(', ')})" end return nil end end def find_by_name(words, nodes=[]) words = words.split unless words.is_a?(Array) nodes << self if words.include?(name) children.each do |c| c.find_by_name(words, nodes) end nodes end end # Public: adds word_wrap method to String for better screen formatting. class String def word_wrap(width=80) # Replace newlines with spaces gsub(/\n/, ' '). # Replace more than one space with a single space gsub(/\s+/, ' '). # Replace spaces at the beginning of the # string with nothing gsub(/^\s+/, ''). # This one is hard to read. Replace with any amount # of space after it with that punctuation and a space gsub(/([\.\!\?\:\,]+)(\s+)?/, '\1 '). # Now add some paragraphs gsub(/<br>/, "\n"). # The meat of the method, replace between 1 and width # characters followed by whitespace or the end of the # line with that string and a newline. This works # because regular expression engines are greedy, # they'll take as many characters as they can. gsub(%r[(.{1,#{width}})(?:\s|\z)], "\\1\n") end end
require 'rails_helper' RSpec.describe Student, type: :model do before :each do Student.create(UIN:'123456789',First_Name:'John',Last_Name:'Smith',Email:'smith@tamu.edu',Phone_Number:'0987654321') end it 'Should Create Student Object' do expect(:index).to eq(:index) end end
module RSence # Namespace for plugin classes and modules module Plugins end end # Contains the PluginBase module which has common methods for the bundle classes require 'rsence/plugins/plugin_base' # guiparser.rb contains the Yaml serializer for gui trees. # It uses JSONRenderer on the client to build user interfaces. require 'rsence/plugins/guiparser' # plugin_sqlite_db.rb contains automatic local sqlite database # creation for a plugin that includes it. require 'rsence/plugins/plugin_sqlite_db' # Interface for plugins in a plugin bundle require 'rsence/plugins/plugin_plugins' # Templates for the main plugin classes. require 'rsence/plugins/plugin' require 'rsence/plugins/gui_plugin' require 'rsence/plugins/multi_gui_plugin' require 'rsence/plugins/servlet' module RSence module Plugins # Creates the runtime Plugin class from Plugin__ # @return [Plugin__] def self.Plugin lambda do |ns| klass = Class.new( Plugin__ ) do def self.ns=(ns) define_method( :bundle_info ) do ns.bundle_info end end end klass.ns = ns if ns klass end end # Creates the runtime GUIPlugin class from GUIPlugin__ # @return [GUIPlugin__] def self.GUIPlugin lambda do |ns| klass = Class.new( GUIPlugin__ ) do def self.ns=(ns) define_method( :bundle_info ) do ns.bundle_info end end end klass.ns = ns if ns klass end end # Creates the runtime MultiGUIPlugin class from MultiGUIPlugin__ # @return [MultiGUIPlugin__] def self.MultiGUIPlugin lambda do |ns| klass = Class.new( MultiGUIPlugin__ ) do def self.ns=(ns) define_method( :bundle_info ) do ns.bundle_info end end end klass.ns = ns if ns klass end end # Creates the runtime Servlet class from Servlet__ # @return [Servlet__] def self.Servlet lambda do |ns| klass = Class.new( Servlet__ ) do def self.ns=(ns) define_method( :bundle_info ) do ns.bundle_info end end end klass.ns = ns if ns klass end end # Loads bundle in an anonymous module with special environment options. # @param [Hash] params # @option params [String] :src_path ('/path/of/the_plugin/the_plugin.rb') The ruby source file to read. # @option params [String] :bundle_path ('/path/of/the_plugin') The plugin bundle directory path. # @option params [String] :bundle_name (:the_plugin) The name of the plugin as it will be registered. # @return [Module] Isolated, anonymous module containing the evaluated source code of +src_path+ def self.bundle_loader( params ) begin mod = Module.new do |m| if RUBY_VERSION.to_f >= 1.9 m.define_singleton_method( :_bundle_path ) do params[ :bundle_path ] end else m.module_eval( <<-END def self._bundle_path; #{params[:bundle_path].inspect}; end END ) end # Makes a full path using the plugin bundle as the 'local path'. # The (optional) +prefix+ is a subdirectory in the bundle, # the +suffix+ is the file extension. def self.bundle_path( path=false, prefix=false, suffix=false ) return _bundle_path if not path if suffix path = "#{path}#{suffix}" unless path.end_with?(suffix) end if prefix path = File.join( prefix, path ) end path = File.expand_path( path, _bundle_path ) return path end def self.inspect; "#<module BundleWrapper of #{self._bundle_path}}>"; end def self.const_missing( name ) if name == :Servlet return Plugins.Servlet.call( self ) elsif name == :Plugin return Plugins.Plugin.call( self ) elsif name == :GUIPlugin return Plugins.GUIPlugin.call( self ) elsif name == :MultiGUIPlugin return Plugins.MultiGUIPlugin.call( self ) else warn "Known const missing: #{name.inspect}" super end end begin plugin_src = params[:src] unless RUBY_VERSION.to_f >= 1.9 plugin_src = "_bundle_path = #{params[:bundle_path].inspect};" + plugin_src end m.module_eval( plugin_src ) rescue SyntaxError => e src_path = params[:src_path] src_path = "<undefined src_path>" if src_path == nil params[:plugin_manager].plugin_error( e, 'BundleLoaderSyntaxError', "The syntax of #{params[:bundle_name]} is invalid.", src_path ) rescue => e src_path = params[:src_path] src_path = "<undefined src_path>" if src_path == nil params[:plugin_manager].plugin_error( e, 'BundleLoaderEvalError', "An error occurred while evaluating the plugin bundle #{params[:bundle_name]}.", src_path ) end end return mod rescue => e src_path = params[:src_path] src_path = "<undefined src_path>" if src_path == nil params[:plugin_manager].plugin_error( e, 'BundleLoaderError', "An error occurred while loading the plugin bundle #{params[:bundle_name]}.", src_path ) end end end end
require_relative "../base" describe SfnParameters::Safe::Ssl do let(:key) { "TEST_KEY" } let(:salt) { "TEST_SALT" } let(:subject) { described_class.new(key: key, salt: salt) } it "should have key set" do expect(subject.arguments[:key]).to eq(key) end it "should have salt set" do expect(subject.arguments[:salt]).to eq(salt) end describe "#new" do context "when key is unset" do let(:key) { nil } it "should raise an ArgumentError" do expect { subject }.to raise_error(ArgumentError) end end context "when salt is unset" do let(:salt) { nil } it "should generate a random salt" do expect(subject.arguments[:salt]).to be_a(String) end end end describe "#lock" do let(:data) { "TEST_DATA" } let(:lock) { subject.lock(data) } it "should return a Hash result" do expect(lock).to be_a(Hash) end it "should include base64 encoded salt" do expect(lock[:salt]).to eq( Base64.urlsafe_encode64(salt) ) end it "should set type of safe used" do expect(lock[:sfn_parameters_lock]).to eq("ssl") end it "should include cipher used" do expect(lock[:cipher]).to eq(described_class.const_get(:DEFAULT_CIPHER)) end it "should base64 encode locked value" do expect(Base64.urlsafe_decode64(lock[:content])).to be_a(String) end it "should encrypt locked value" do expect(Base64.urlsafe_decode64(lock[:content])).not_to eq(data) end end describe "#unlock" do let(:data) { "TEST_DATA" } it "should properly unlock locked data" do locked = subject.lock(data) expect(Base64.urlsafe_decode64(locked[:content])).not_to eq(data) expect(subject.unlock(locked)).to eq(data) end context "with missing content" do it "should raise an ArgumentError" do locked = subject.lock(data) locked.delete(:content) expect { subject.unlock(locked) }.to raise_error(ArgumentError) end end context "with missing iv" do it "should raise an ArgumentError" do locked = subject.lock(data) locked.delete(:iv) expect { subject.unlock(locked) }.to raise_error(ArgumentError) end end context "with missing salt" do it "should raise an ArgumentError" do locked = subject.lock(data) locked.delete(:salt) expect { subject.unlock(locked) }.to raise_error(ArgumentError) end end end end
class SendUserActivityAlertsJob < ApplicationJob def perform(user_con_profile, event) SendUserActivityAlertsService.new( user_con_profile: user_con_profile, event: event ).call! end end
require "selenium-webdriver" require "test/unit" class Collection_Share_Class < Test::Unit::TestCase def setup @driver = Selenium::WebDriver.for :chrome @driver.get('https://noteswsd2021.herokuapp.com/') @driver.manage.window.maximize end def test_collection @driver.find_element(:name, "username").send_keys "Diego" @driver.find_element(:name, "password").send_keys "Diego1234" @driver.find_element(:name, "commit").click sleep 1 #Se crea la coleccion @driver.get('https://noteswsd2021.herokuapp.com/notecollections/new') @driver.find_element(:name, "notecollection[name]").send_keys "Nueva coleccion Diego" sleep 0.3 @driver.find_element(:name, "commit").click sleep 2 assert(@driver.find_element(:id => "table-index").text.include?("Nueva coleccion Diego"),"Assertion Failed") #Se añade nota a la coleccion de la ultima posicion que sera la que acabamos de añadir table=@driver.find_element(:id => "table-index") row_count=table.all(:css, 'tr').size fila=@driver.find_elements(:xpath => "//table[@id='table-index']/tbody/tr")[row_count-1] fila.find_element(:id, "btn3-index").click sleep 0.5 #obtengo la primera fila donde estara la nota y el boton de añadir fila=@driver.find_elements(:xpath => "//table[@id='table-add']/tbody/tr")[2] #obtengo el nombre de la primera nota para luego comprobar si la añade bien nombre=fila.text.split("\n")[0] #añado la primera nota fila.find_element(:id, "tr2-add").click sleep 1 #ahora la comparto fila=@driver.find_elements(:xpath => "//table[@id='table-index']/tbody/tr")[row_count-1] collectionShared=fila.text.split("\n")[0] fila.find_element(:id, "btn4-index").click sleep 1 filaUser=@driver.find_elements(:xpath => "//table[@id='table-share']/tbody/tr")[4] filaUser.find_element(:id, "td4-share").click #assert(nota.find_element(:id => "td-show").text.include?(nombre),"Assertion Failed") sleep 0.5 @driver.get('https://noteswsd2021.herokuapp.com/logout') sleep 1 @driver.get('https://noteswsd2021.herokuapp.com') sleep 0.5 @driver.find_element(:name, "username").send_keys "Maria" @driver.find_element(:name, "password").send_keys "Maria1234" sleep 0.3 @driver.find_element(:name, "commit").click sleep 0.4 @driver.get('https://noteswsd2021.herokuapp.com/notecollectionsUser?user=Maria') sleep 1 #ahora la busco para el asserts assert(@driver.find_element(:id => "table-index").text.include?(collectionShared),"Assertion Failed") end end
module Decoder class Country include ::CommonMethods attr_accessor :code, :name def initialize(args) self.code = args[:code].to_s self.name = args[:name] self.states = Decoder.locale[Decoder.i18n][self.code][:states] end def states @states end def states=(_states) @states = _states end alias_method :provinces, :states alias_method :territories, :states def [](_code) _code = _code.to_s.upcase state = states[_code] if state.is_a?(Hash) fips = state[:fips] state = state[:name] # counties = state[:counties] end Decoder::State.new(:code => _code, :name => state, :fips => fips) end def by_fips(fips) fips = fips.to_s state = states.detect do |state_code,info| info.is_a?(Hash) && info[:fips] == fips end self[state.first] end end end
# coding: utf-8 require 'nokogiri' require 'mechanize' require 'logger' module GradeAPI @@login_uri = "https://innsida.ntnu.no/sso/?target=KarstatProd" @@report_path = "/karstat/makeReport.do" @@report_uri = "http://www.ntnu.no#{@@report_path}" @@agent = Mechanize.new @@lang_map = [ :candidates, :at_exam, :passed, :failed, :cancelled, :fail_ratio, :grade_average, :with_sick_note, :fail_before_exam, ] @@option_key_map = { :year => ["fromYear", "toYear"], :semester => ["fromSemester", "toSemester"], } @@option_value_map = { :semester => { "s" => "VÅR", "f" => "HØST", } } def self.config @@config ||= {} end def self.config=(hash) @@config = hash end def self.configure yield config end def self.login @@agent.auth(ENV['KARSTAT_USERNAME'], ENV['KARSTAT_PASSWORD']) @@agent.get(@@login_uri) end class << self def get(code, options={}) puts "Got options: #{options.inspect}" html_doc = Nokogiri::HTML(raw(code, options)) tables = html_doc.css(".questTop") if tables.length == 2 meta, grades = tables stats = { :meta => handle_meta(meta), :grades => handle_grades(grades) } stats[:grades][:f] = stats[:meta][:failed][:total] stats end end protected def handle_meta(meta_doc) rows = meta_doc.css("tr.tableRow") meta = {} i = 0 rows.each do |row| cols = row.css("td") if cols.length == 4 field, total, women, men = cols index = field.text.strip.sub(/:$/, "") meta[@@lang_map[i]] = { :total => total.text.strip.to_i, :women => women.text.strip.to_i, :men => men.text.strip.to_i, } end i += 1 end meta end def handle_grades(grades_doc) rows = grades_doc.css(".tableRow") grades = {} rows.each do |row| grade, total, women = row.css("td") grades[grade.text.strip.downcase.to_sym] = total.text.strip.to_i end grades end def raw(code, options={}) login report_page = @@agent.post(@@report_uri) form = report_page.form_with(:action => @@report_path) form['courseName'] = code # Insert provided options in a safe way options.each do |key, value| if @@option_key_map.has_key?(key) if @@option_value_map.has_key?(key) and @@option_value_map[key].has_key?(value) field_value = @@option_value_map[key][value] else field_value = value end @@option_key_map[key].each do |field| form[field] = field_value puts "Filled in: #{field} with '#{field_value}'" end end end result = form.submit result.body end end end
# frozen_string_literal: true module ActiveRecord class SchemaMigration < ActiveRecord::Base # :nodoc: class << self def table_exists? connection.table_exists?(table_name) end end end end
class AddExchangeRateDateRangeConstraint < ActiveRecord::Migration def up execute <<-eos CREATE FUNCTION unique_exchange_rate_date_range(record_id integer, new_anchor text, new_float text, new_start_date date, new_end_date date) RETURNS boolean AS $$ BEGIN IF (SELECT count(*) FROM exchange_rates WHERE new_anchor = anchor AND new_float = float AND record_id != id AND daterange(new_start_date, new_end_date) && daterange(starts_on, ends_on) ) = 0 THEN RETURN TRUE; ELSE RETURN FALSE; END IF; END; $$ LANGUAGE plpgsql; alter table exchange_rates add constraint unique_date_ranges check (unique_exchange_rate_date_range(id, anchor, float, starts_on, ends_on)); eos end def down execute <<-eos alter table exchange_rates drop constraint unique_date_ranges; drop function unique_exchange_rate_date_range(integer, text, text, date, date); eos end end
class SongsController < ApplicationController before_filter :is_admin, :except => [:index, :show] respond_to :html, :json def new @song = Song.new respond_with @song end def create @song = Song.new(params[:song]) if @song.save respond_with @song else redirect_to new_song_path end end def show @song = Song.find(params[:id]) respond_with @song end def index @songs = Song.order(:title) @setlists = Setlist.order("created_at DESC") respond_with @songs end def edit @song = Song.find(params[:id]) respond_with @song end def update @song = Song.find(params[:id]) if @song.update_attributes(params[:song]) respond_with @song else redirect_to edit_song_path(@song) end end def destroy @song = Song.find(params[:id]) @song.destroy redirect_to song_path(@song) end private def is_admin if !signed_in? || !current_user.admin? flash[:notice] = "You have to be an admin to do that." redirect_to root_path end end end
# frozen_string_literal: true class GroupInstructorsController < ApplicationController before_action :admin_required def index group_instructors = GroupInstructor .includes(group_semester: :semester, group_schedule: :group) .order('group_schedules.weekday, group_schedules.start_at, groups.from_age') .to_a group_instructors.sort_by! do |gi| [ gi.group_semester.semester.current? ? 0 : 1, gi.group_semester.semester.future? ? 0 : 1, if gi.group_semester.semester.future? gi.group_semester.semester.start_on else Date.current - gi.group_semester.semester.end_on end, gi.group_schedule.group.from_age, gi.group_schedule.weekday, -(gi.member.current_rank&.position || -999), ] end @semesters = group_instructors.group_by { |gi| gi.group_semester.semester } return unless Semester.current && @semesters.exclude?(Semester.current) @semesters = { Semester.current => [] }.update @semesters end def show @group_instructor = GroupInstructor.find(params[:id]) end def new @group_instructor ||= GroupInstructor.new params[:group_instructor] load_form_data render action: :new end def edit @group_instructor ||= GroupInstructor.find(params[:id]) load_form_data render action: :edit end def create convert_semester_id @group_instructor = GroupInstructor.new(params[:group_instructor]) if @group_instructor.save anchor = :next_tab if @group_instructor.group_semester.semester == Semester.next redirect_to group_instructors_path(anchor: anchor), notice: 'Ny gruppeinstruktør er registrert.' else new end end def update convert_semester_id @group_instructor = GroupInstructor.find(params[:id]) if @group_instructor.update(params[:group_instructor]) redirect_to group_instructors_path, notice: 'GroupInstructor was successfully updated.' else edit end end def destroy @group_instructor = GroupInstructor.find(params[:id]) anchor = :next_tab if @group_instructor.group_semester.semester == Semester.next @group_instructor.destroy redirect_to group_instructors_url(anchor: anchor), notice: 'Ny gruppeinstruktør er slettet.' end private def load_form_data @group_schedules = GroupSchedule.includes(:group).references(:groups) .order('weekday, groups.from_age').to_a.select { |gs| gs.group.active? } instructors = Member.instructors.sort_by(&:current_rank).reverse @group_instructors = [ instructors, Rank.kwr.find_by(name: '4. kyu').members.active.sort_by(&:name).uniq - instructors ] @semesters ||= Semester.order('start_on DESC').limit(10).to_a end def convert_semester_id semester_id = params[:group_instructor].delete(:semester_id) return unless semester_id.present? && params[:group_instructor][:group_schedule_id].present? group_schedule = GroupSchedule.find(params[:group_instructor][:group_schedule_id]) group_semester = GroupSemester .where(group_id: group_schedule.group_id, semester_id: semester_id).first params[:group_instructor][:group_semester_id] = group_semester.id end end
class ViewedCallsMutation < Types::BaseMutation description "Marks all calls as viewed" argument :contact_id, ID, required: false field :success, Boolean, null: true policy ApplicationPolicy, :logged_in? def resolve calls = if input.contact_id Call.for_contact(contact) else Call end if calls.for_user(current_user).mark_viewed {success: true} else {success: false} end end private def contact Contact.find_by!(id: input.contact_id, user: current_user) end end
class AddIpToPoints < ActiveRecord::Migration[5.2] def change add_column :points, :ip, :string add_column :points, :subnet_mask, :string add_column :points, :dns1, :string add_column :points, :dns2, :string end end
class RenameAverageDriverLengthToAverageDriveLengthInStatistics < ActiveRecord::Migration def change rename_column :statistics, :average_driver_length, :average_drive_length end end
# frozen_string_literal: true require 'yaml' require_relative 'station' class RailroadMenu attr_reader :action_menu, :exit_index def initialize @action_menu = parse_menu_from_file('menu.yml') @exit_index = nil end def print_menu puts 'Выберите действие:' action_menu.each_with_index do |item, index| case item[:type] when :separator then puts item[:title].nil? ? '' : "\n[#{item[:title]}]" when :exit @exit_index = index print_menu_item(index, item) else print_menu_item(index, item) end end end def parse_menu_from_file(file_name) raise StandardError, "Файл меню не найден (#{file_name})" unless File.exist?(file_name) raise StandardError, "Файл меню пустой (#{file_name})" if File.zero?(file_name) menu_items = YAML.load_file(file_name) raise StandardError, 'Ошибка формата меню' unless menu_items.is_a?(Array) menu_items rescue StandardError => e puts e end def print_menu_item(index, item) puts "[#{index}] #{item[:title]}" end def title(index) action_menu[index][:title] end def message(index) action_menu[index][:message] end end
# frozen_string_literal: true module Api module V1 class SessionsController < ApplicationController def create user = User.find_by(email: params[:email]) if user&.valid_password?(params[:password]) @current_user = user token = generate_token s = Session.create(user_id: @current_user.id, token: token) s.save response.set_header('token', s.token) # render json: { messages: {'Successfully Logged In'} }, status: :ok else render json: { errors: { 'email or password' => ['is invalid'] } }, status: :unprocessable_entity end end def destroy @session = Session.find_by(token: @current_user_token) @session.destroy end end end end
require 'spec_helper' require 'support/test_classes' describe 'enumerable syntax' do let(:mapper) { Perpetuity[Article] } let(:current_time) { Time.now } let(:foo) { Article.new("Foo #{Time.now.to_f}", '', nil, current_time - 60) } let(:bar) { Article.new("Bar #{Time.now.to_f}", '', nil, current_time + 60) } before do mapper.insert foo end it 'finds a single object based on criteria' do expect(mapper.find { |a| a.title == foo.title }).to be == foo end context 'excludes objects based on criteria' do before do mapper.insert bar end it 'excludes on equality' do articles = mapper.reject { |a| a.title == bar.title }.to_a expect(articles).to include foo expect(articles).not_to include bar end it 'excludes on inequality' do articles = mapper.reject { |a| a.published_at <= current_time }.to_a expect(articles).to include bar expect(articles).not_to include foo end it 'excludes on not-equal' do articles = mapper.reject { |a| a.title != foo.title }.to_a expect(articles).to include foo expect(articles).not_to include bar end it 'excludes on regex match' do articles = mapper.reject { |a| a.title =~ /Foo/ }.to_a expect(articles).to include bar expect(articles).not_to include foo end end end
require 'minitest/autorun' require 'modelstack' class ModelStackTest < Minitest::Test def test_version assert_equal "0.0.0", ModelStack::VERSION end end
class CreateDownloadData < ActiveRecord::Migration def change create_table :download_data do |t| t.date :date t.integer :audio_file_id t.integer :downloaded t.integer :hits t.timestamps end end end
# ActiveAdmin.register Product do # # scope :unreleased # index do # column :name # column :description # column :title # column :stock # column :image # column :user # column :category # column "Release Date", :released_at # column :price, :sortable => :price do |product| # number_to_currency product.price # end # actions # end # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # # permit_params :list, :of, :attributes, :on, :model # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if resource.something? # permitted # end # end
RSpec.describe "shared/activities/_tab_nav_item" do subject do render partial: "shared/activities/tab_nav_item", locals: {tab: tab, path: path, "@tab_name": tab_name} Capybara.string(rendered) end let(:path) { "https://example.com" } describe "controller name matches the current tab" do let(:tab_name) { "details" } let(:tab) { "details" } it "is rendered correctly" do expect(subject).to have_css("li.govuk-tabs__list-item--selected") within "a.govuk-tabs__tab" do expect(subject).to have_link(path) expect(subject["aria-selected"]).to be_truthy end end end describe "controller name doesn't match the current tab" do let(:tab_name) { "another_tab" } let(:tab) { "details" } it "is rendered correctly" do expect(subject).to have_no_css("li.govuk-tabs__list-item--selected") within "a.govuk-tabs__tab" do expect(subject).to have_link(path) expect(subject["aria-selected"]).to be_falsey end end end end
class BrochureSelection < ActiveRecord::Base belongs_to :brochure belongs_to :reservation validates :brochure, presence: true validates :percent, presence: true, :if => ->{ self.reservation == true } # validates_presence_of :brochure acts_as_paranoid # Brochure method to include associations with deleted brochures # Used on reservation index so deleted brochures are included (prevent error) def brochure_del Brochure.with_deleted.find(brochure_id) end end
# frozen_string_literal: true # run a test task require 'spec_helper_acceptance' windows = os[:family] == 'windows' describe 'linux package task', unless: windows do describe 'install action' do it 'installs rsyslog' do apply_manifest("package { 'rsyslog': ensure => absent, }") result = run_bolt_task('package::linux', 'action' => 'install', 'name' => 'rsyslog') expect(result.exit_code).to eq(0) expect(result['result']).to include('status' => %r{install}) expect(result['result']).to include('version') end it 'errors gracefully when bogus package requested' do result = run_bolt_task('package::linux', { 'action' => 'install', 'name' => 'foo' }, expect_failures: true) # older EL platforms may report that the bogus package is uninstalled, if result['result']['status'] == 'failure' expect(result['result']).to include('status' => 'failure') expect(result['result']['_error']).to include('msg') expect(result['result']['_error']).to include('kind' => 'bash-error') expect(result['result']['_error']).to include('details') elsif result['result']['status'] == 'success' || result['result']['status'] == 'uninstalled' expect(result['result']).to include('status' => 'uninstalled') else raise "Unexpected result: #{result}" end end end describe 'status action' do it 'status rsyslog' do apply_manifest("package { 'rsyslog': ensure => present, }") result = run_bolt_task('package::linux', 'action' => 'status', 'name' => 'rsyslog') expect(result.exit_code).to eq(0) expect(result['result']).to include('status' => %r{install}) expect(result['result']).to include('version') end end describe 'uninstall action' do it 'uninstall rsyslog' do apply_manifest("package { 'rsyslog': ensure => present, }") result = run_bolt_task('package::linux', 'action' => 'uninstall', 'name' => 'rsyslog') expect(result.exit_code).to eq(0) expect(result['result']).to include('status' => %r{not install|deinstall|uninstall}) end end describe 'upgrade' do it 'upgrade rsyslog' do apply_manifest("package { 'rsyslog': ensure => present, }") result = run_bolt_task('package::linux', 'action' => 'upgrade', 'name' => 'rsyslog') expect(result.exit_code).to eq(0) expect(result['result']).to include('old_version') expect(result['result']).to include('version') end end end
json.array!(@our_advantages) do |our_advantage| json.extract! our_advantage, :id, :title, :description json.url our_advantage_url(our_advantage, format: :json) end
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../../lib")) require "zznamezz_test_case" class TC_R001_01_AN_EXAMPLE_TEST < Test::Unit::TestCase include ZZnamezzTestCase def setup # specify setup parameters @certificate = :regular # this is the default user for this test @initialBrowser = :none # if you want this test to navigate to your webapp automatically as part of setup, change this value to the value referring to your webapp super # must call super so that the common setup method in ZZnamezzTestCase is called end def test_r001_01_an_example_test ############################################################################################ # PURPOSE : # Verify that <description of your test's intent> # # PRECONDITIONS : # <list your preconditions> ############################################################################################ filename = "data_for_example_test.csv" # file must be in the data/ directory data = @help.read_csv_test_data(filename) header = data.shift # Step 1 : # Send a request to the yyrawnameyy API Options method random_row = data.random search_term = random_row[0] expected_result_count = random_row[1] # This is too raw - it would be better to bundle these lines into a separate "search_options" method, # with additional validation (e.g. to throw a clean error if the request failed) @client = @help.get_rest_client(:options, @certificate, search_term) json = client.get response = JSON.pretty_unparse(json) # Expected Result : # The request has succeeded & returned the expected results # This is quite brittle # A better approach is to create a new class which would parse the response & convert # it into a bespoke Object, so that the various values could be accessed in a better OO-fashion. # E.g. response.number_of_results. The object could also have extra methods, # e.g. response.check_results_are_valid, and so on. assert_equal(expected_result_count, response["number_of_results"], "The search request did not return the expected number of results") # Step 2 : # Log in to yyrawnameyy xxabbrevxx_login # Expected Result : # The yyrawnameyy homepage is displayed assert(xxabbrevxxHomepage.displayed?, "The yyrawnameyy homepage is not displayed") # Step 3 : # Enter in a search term and click the Search button. data.each do |row| search_term = row[0] expected_result_text = row[2] puts "Will now search for '#{term}'; expect to see '#{expected_result_text}'" xxabbrevxxHomepage.term = search_term xxabbrevxxHomepage.click_search # Expected Result : # Results are displayed assert(xxabbrevxxSearchResults.displayed?, "The yyrawnameyy search results page is not displayed") assert_equal(expected_result_text, xxabbrevxxSearchResults.result, "The yyrawnameyy search results page did not display the expected result") # Step 4 : # Return to the previous page browser.back # Expected Result : # The yyrawnameyy homepage is displayed assert(xxabbrevxxHomepage.displayed?, "The yyrawnameyy homepage is not displayed") # Step 5 : # Repeat steps 3 and 4 for a few more search terms # Actions performed in above steps # Expected Result : # Results are displayed for each term # Assertions performed in above steps end # end .each end end
require 'spec_helper' require 'legion/json' SimpleCov.command_name 'lib/legion/json' RSpec.describe Legion::Json do before(:all) { @json_string = '{"foo":"bar"}' } it 'has a version number' do expect(Legion::Json::VERSION).not_to be nil end it 'can load a parser for current platform' do hash = Legion::JSON.load(@json_string) expect(hash).to eq(foo: 'bar') string = Legion::JSON.dump({ baz: 'qux' }) expect(string).to eq('{"baz":"qux"}') end it 'can load json correctly' do hash = Legion::JSON.load(@json_string) string = Legion::JSON.dump(hash) expect(string).to eq(@json_string) end it 'can handle large json objects' do hash = Legion::JSON.load('{"foo":"bar", "cake": "sugar", "test":{"ruby":"gem", "java": "jar"}}') expect(hash[:foo]).to eq('bar') expect(hash[:cake]).to eq('sugar') expect(hash[:test]).not_to be_empty expect(hash[:test][:ruby]).to eq('gem') expect(hash[:test][:java]).to eq('jar') expect(hash[:test][:thing]).to be_nil expect(hash[:nil]).to be_nil end it 'matches when switched back to json' do json = '{"foo":"bar"}' hash = Legion::JSON.load(json) return_json = Legion::JSON.dump(hash) expect(return_json).to eq(json) end it 'will not sq' do hash = Legion::JSON.load(@json_string) expect(hash).not_to eq(foo: 'baz') expect(hash).not_to eq(bar: 'foo') end it 'will throw exception' do expect { Legion::JSON.load('{"foo":"bar}') }.to raise_error(Legion::JSON::ParseError) expect { Legion::JSON.load('{"foo":"bar"') }.to raise_error(Legion::JSON::ParseError) expect { Legion::JSON.load('{foo:"bar}') }.to raise_error(Legion::JSON::ParseError) expect { Legion::JSON.load('{') }.to raise_error(Legion::JSON::ParseError) end end
require 'spec_helper' describe CommentsController do #Create method test describe "POST create" do #create a page before each operation (method call) before(:each) do page = FactoryGirl.create(:page) end #Testing valid attributes as a params context "with valid attributes" do #Testing that the qustion is saved in the database it "creates a new Comment" do expect{ post :create, :comment => {:body=> "test comment",:assigned_part => "1"}, :page_id => 1 }.to change(Comment,:count).by(1) end #Testing that it is redirected back to the revieweing page(reviewer page) with the notice it "redirects to the new Comment" do post :create, :comment => {:body=> "test comment",:assigned_part => "1"}, :page_id => 1 response.should redirect_to ("/pages/reviewer?id=#{assigns(:page).id}&notice=Comment+was+successfully+created.") end end #Testing valid attributes as a params context "with invalid attributes" do #Testing that the qustion is not saved in the database it "does not save the new Comment" do expect{ post :create, :comment => {:body=> "",:assigned_part => "1"}, :page_id => 1 }.to_not change(Comment,:count) end #Testing that it is redirected back to the revieweing page(reviewer page) with the notice it "redirects to reviewing page (reviewer page)" do post :create, :comment => {:body=> "",:assigned_part => ""}, :page_id => 1 response.should redirect_to ("/pages/reviewer?id=#{assigns(:page).id}&notice=Comment+could+not+be+saved.+Please+fill+in+all+fields") end end end # Testing the deletion of a comment describe 'DELETE destroy' do # Creating a comment and a page before each method call before :each do @page = FactoryGirl.create(:page) @comment = FactoryGirl.create(:comment) end #Testing that the qustion is removed from the database it "deletes the comment" do expect{ delete :destroy, id: @comment ,page_id: @page }.to change(Comment,:count).by(-1) end #Testing that it is redirected back to the revieweing page(reviewer page) with the notice it "redirects to reviewing page" do delete :destroy, id: @comment,page_id: @page response.should redirect_to ("/pages/reviewer?id=#{assigns(:page).id}&notice=Comment+was+successfully+deleted.") end end end
class Tshirt < ApplicationRecord belongs_to :user validates :name, presence: true validates :description, presence: true, length: { maximum: 150 } validates :photo, presence: true monetize :price_cents belongs_to :user has_many :items mount_uploader :photo, PhotoUploader def self.tagsArray(limit) dirtyArray = [] Tshirt.all.each do |tshirt| if tshirt.tags != nil dirtyArray << tshirt.tags.strip.split(", ") end end cleanArray = dirtyArray.flatten cleanHash = Hash[cleanArray.uniq.map {|v| [v, cleanArray.count(v)] }].sort_by {|k,v| -v }[0...limit.to_i] finalArray = cleanHash.map {|k,v| k }.sort end end
class CreateHospitalsProcedures < ActiveRecord::Migration def change create_table :hospitals_procedures do |t| t.integer :drg_id t.string :drg_def t.integer :provider_id t.string :provider_name t.integer :total_discharges t.float :avg_covered_charges t.float :avg_total_payments end end end
require 'spec_helper' describe "project_files/new" do before(:each) do assign(:project_file, stub_model(ProjectFile, :project => nil, :url => "MyString", :data => "" ).as_new_record) end it "renders new project_file form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form[action=?][method=?]", project_files_path, "post" do assert_select "input#project_file_project[name=?]", "project_file[project]" assert_select "input#project_file_url[name=?]", "project_file[url]" assert_select "input#project_file_data[name=?]", "project_file[data]" end end end
Rails.application.routes.draw do # 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 'users#new' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/logout', to: 'sessions#destroy' post '/create_task', to: 'tasks#create' resources :users, only: [:new, :create, :show] do resources :categories, only: [:index, :create, :update] do resources :tasks, only: [:create, :update] end end end
class Candy attr_accessor :candy def initialize(candy) @candy = candy end def type candy end end
# frozen_string_literal: true class CalculatorService < Calculator::Calculator::Service def unary_operation(service_request, _call) @received_metadata = _call.metadata case service_request.operand when '+' result = service_request.x * 1 when '-' result = service_request.x * -1 else raise GRPC::BadStatus.new_status_exception(code = UNIMPLEMENTED, details = 'operand not implemented') end Calculator::UnaryResponse.new( x: service_request.x, operand: service_request.operand, result: result.to_s ) end def multi_unary_operation(service_request, _call) @received_metadata = _call.metadata case service_request.operand when '+' results = service_request.xs.collect { |x| (x * 1).to_s } when '-' results = service_request.xs.collect { |x| (x * -1).to_s } else raise GRPC::BadStatus.new_status_exception(code = UNIMPLEMENTED, details = 'operand not implemented') end Calculator::MultiUnaryResponse.new( xs: service_request.xs.to_a, operand: service_request.operand, results: results ) end def binary_operation(service_request, _call) @received_metadata = _call.metadata case service_request.operand when '+' result = service_request.x + service_request.y when '-' result = service_request.x - service_request.y when '==' bool_result = service_request.x == service_request.y else raise GRPC::BadStatus.new_status_exception(code = UNIMPLEMENTED, details = 'operand not implemented') end Calculator::BinaryResponse.new( x: service_request.x, y: service_request.y, operand: service_request.operand, result: result.to_s, boolean_result: bool_result ) end def range(service_request, _call) @received_metadata = _call.metadata Range.new(service_request.s, service_request.e).obtain_range.each end def current_time(request, _call) @received_metadata = _call.metadata Calculator::Timestamp.new(ms: (1000 * Time.now.to_f).to_i) end def echo_time(request, _call) @received_metadata = _call.metadata Calculator::TimeResponse.new( timestamp: request.timestamp ) end def get_metadata(key) @received_metadata[key] end def get_all_metadata @received_metadata end class Range def initialize(s, e) @s = s @e = e @enumerable = [] end def obtain_range (@s..@e).each do |i| @enumerable.push(Calculator::RangeResponse.new(x: i, numeric_result: i, boolean_result: i % 2 == 1)) end @enumerable end end end
class Airport < ApplicationRecord has_many :airport_flights has_many :flights, through: :airport_flights end
module Libis module Workflow VERSION = '2.1.10' unless const_defined? :VERSION # the guard is against a redefinition warning that happens on Travis end end
class Doctor::SessionsController < ApplicationController layout "empty" before_action :require_doctor_signin, :only => :destroy skip_before_filter :session_expiry skip_before_filter :update_activity_time def new if doctor_signed_in? redirect_to '/doctor/dashboard' end end def create @doctor = Doctor.find_by(email: params[:session][:email].downcase) if @doctor && @doctor.authenticate(params[:session][:password]) if @doctor.email_confirmed doctor_sign_in(@doctor) if session[:doctor_return_to] redirect_to session[:doctor_return_to] session[:doctor_return_to] = nil else redirect_to doctor_dashboard_path end else flash[:error_messages] = 'Your account is not activated. Please refer to the activiation email that was sent to your email address.' redirect_to doctor_signin_path end else flash[:error_messages] = 'Invalid email/password combination.' redirect_to doctor_signin_path end end def destroy doctor_sign_out redirect_to '/doctor' end def destroy_client_session_expiry session[:doctor_return_to] = request.referer doctor_sign_out render 'doctor/sessions/redirect_login_session_expiry', :layout=>false end end
class Message < ApplicationRecord belongs_to :conversation belongs_to :user validates_presence_of :body, :conversation_id, :user_id validates :body, :length => { :maximum => 1000, :minimum => 1 } def convo_time created_at.strftime("%d/%m/%y at %l:%M %p") end def message_time created_at.strftime("%l:%M %p") end end
class UserMailer < ApplicationMailer def user_created(user) @user = user @url = new_user_session_url @title = "Thanks for joining aepi.org.au, #{@user.first_name}" mail(to: @user.email, subject: @title) end def user_created_admin_notification(user, new_user) @user = user @new_user = new_user @url = users_url @title = "#{@new_user.full_name} has joined aepi.org.au" mail(to: @user.email, subject: @title) end end
module Api class InvalidToken < StandardError end class AccessDenied < StandardError end class InvalidParams < StandardError end end
require "rails_helper" feature "Account Creation" do scenario "allow acsess to Log in page" do visit new_user_session_path Capybara.ignore_hidden_elements=false expect(page).to have_content 'login form anchor for capybara' Capybara.ignore_hidden_elements=true end scenario "allow acsess to Registration page" do visit new_user_registration_path expect(page).to have_content 'Registration' end scenario "allow gest to create acount" do sign_up expect(page).to have_content I18n.t 'devise.registrations.signed_up' end end
require 'active_support/concern' module ApiPresenter module Concerns module Presentable extend ActiveSupport::Concern private # Instantiates presenter for the given relation, array of records, or single record # # @example Request with included records # GET /api/posts?include=categories,subCategories,users # # @example Request with policies # GET /api/posts?policies=true # # @example Request with included records and policies # GET /api/posts?include=categories,subCategories,users&policies=true # # @example Request with count only # GET /api/posts?count=true # # @example PostsController # include ApiPresenter::Concerns::Presentable # # def index # posts = Post.page # present posts # end # # def show # @post = Post.find(params[:id]) # present @post # end # # @param relation_or_record [ActiveRecord::Relation, Array<ActiveRecord::Base>, ActiveRecord::Base] # def present(relation_or_record) klass, relation = if relation_or_record.is_a?(ActiveRecord::Relation) [relation_or_record.klass, relation_or_record] else record_array = Array.wrap(relation_or_record) [record_array.first.class, record_array] end @presenter = presenter_klass(klass).call( current_user: defined?(current_user) ? current_user : nil, relation: relation, params: params ) end # Progressive search for klass's Presenter def presenter_klass(klass) "#{klass.name}Presenter".safe_constantize || "#{klass.base_class.name}Presenter".safe_constantize || "ApplicationApiPresenter".safe_constantize || ApiPresenter::Base end end end end
class AddIndexOnMachineIdToSearsRegistrations < ActiveRecord::Migration def self.up add_index :sears_registrations, :machine_id end def self.down drop_index :sears_registrations, :machine_id end end
require 'spec_helper' feature 'Viewing a workshop page' do let(:workshop) { Fabricate(:sessions) } let(:member) { Fabricate(:member) } scenario "A logged-out user can view an event" do visit workshop_path workshop expect(page).to be end scenario "A logged-in user can view an event" do login member visit workshop_path workshop expect(page).to be end scenario "A logged-out user viewing an event is invited to sign up or sign in" do visit workshop_path workshop expect(page).to have_content("Sign up") expect(page).to have_content("Log in") end scenario "A logged-in user viewing a past event cannot interact with that event" do workshop.update_attribute(:date_and_time, 2.weeks.ago) login member visit workshop_path workshop expect(page).not_to have_button("Attend as a student") expect(page).not_to have_button("Attend as a coach") expect(page).not_to have_button("Join the student waiting list") expect(page).not_to have_button("Join the coach waiting list") expect(page).to have_content("already happened") end scenario "A logged-in user who's not attending can attend an imminent event" do workshop.update_attribute(:date_and_time, Date.today) workshop.update_attribute(:time, 2.hours.from_now) login member visit workshop_path workshop expect(workshop.attendee? member).to be false expect(page).to have_button("Attend as a student") expect(page).to have_button("Attend as a coach") click_button "Attend as a student" expect(workshop.attendee? member).to be true expect(page).to have_content("You're coming to Codebar!") expect(current_path).to eq(added_workshop_path workshop) end scenario "A logged-in user who's attending an imminent event cannot interact with that event" do workshop.update_attribute(:date_and_time, Date.today) workshop.update_attribute(:time, 2.hours.from_now) Fabricate(:student_session_invitation, attending: true, sessions: workshop, member: member) expect(workshop.attendee? member).to be true login member visit workshop_path workshop expect(page).not_to have_button("Attend as a student") expect(page).not_to have_button("Attend as a coach") expect(page).to have_content "If you can no longer make it, email us" end scenario "A logged-in user on the waiting list can remove themselves from the waiting list for an imminent event" do workshop.update_attribute(:date_and_time, Date.today) workshop.update_attribute(:time, 2.hours.from_now) invite = Fabricate(:student_session_invitation, sessions: workshop, member: member) WaitingList.add(invite) login member visit workshop_path workshop expect(workshop.waitlisted? member).to be true click_button "Leave the waiting list" expect(current_path).to eq(removed_workshop_path workshop) expect(workshop.waitlisted? member).to be false end scenario "A logged-in user viewing a future event with student space can register to attend" do login member visit workshop_path workshop expect(workshop.attendee? member).to be false click_button "Attend as a student" expect(page).to have_content("You're coming to Codebar!") expect(current_path).to eq(added_workshop_path workshop) expect(workshop.attendee? member).to be true expect(workshop.attending_students.map(&:member)).to include(member) expect(workshop.attending_coaches.map(&:member)).not_to include(member) end scenario "A logged-in user registering to attend an event doesn't receive an invite email" do login member visit workshop_path workshop expect { click_button "Attend as a student"}.not_to change { ActionMailer::Base.deliveries.count } end scenario "A logged-in user viewing a future event without student space can join the student waiting list" do workshop.host.update_attribute(:seats, 0) login member visit workshop_path workshop expect(workshop.waitlisted? member).to be false expect(page).not_to have_button("Attend as a student") expect(page).to have_button("Join the student waiting list") click_button "Join the student waiting list" expect(current_path).to eq(waitlisted_workshop_path workshop) expect(workshop.waitlisted? member).to be true expect(workshop.attendee? member).to be false end scenario "A logged-in user viewing a future event with coach space can register to attend" do login member visit workshop_path workshop expect(workshop.attendee? member).to be false click_button "Attend as a coach" expect(page).to have_content("You're coming to Codebar!") expect(current_path).to eq(added_workshop_path workshop) expect(workshop.attendee? member).to be true expect(workshop.attending_students.map(&:member)).not_to include(member) expect(workshop.attending_coaches.map(&:member)).to include(member) end scenario "A logged-in user viewing a future event without coach space can join the coach waiting list" do workshop.host.update_attribute(:seats, 0) login member visit workshop_path workshop expect(workshop.waitlisted? member).to be false expect(page).not_to have_button("Attend as a coach") expect(page).to have_button("Join the coach waiting list") click_button "Join the coach waiting list" expect(current_path).to eq(waitlisted_workshop_path workshop) expect(workshop.waitlisted? member).to be true expect(workshop.attendee? member).to be false end scenario "A logged-in user signed up on the student attendance list sees they are attending" do Fabricate(:student_session_invitation, attending: true, sessions: workshop, member: member) expect(workshop.attendee? member).to be true login member visit workshop_path workshop expect(page).not_to have_button("Attend as a student") expect(page).not_to have_button("Join the student waiting list") expect(page).to have_text("You're attending this event") expect(page).to have_button("Cancel your attendance") end scenario "A logged-in user signed up on the student attendance list can remove themselves from the event" do Fabricate(:student_session_invitation, attending: true, sessions: workshop, member: member) expect(workshop.attendee? member).to be true login member visit workshop_path workshop click_button "Cancel your attendance" expect(current_path).to eq(removed_workshop_path workshop) expect(workshop.attendee? member).to be false expect(workshop.waitlisted? member).to be false end scenario "A logged-in user signed up on the coach attendance list sees they are attending" do Fabricate(:coach_session_invitation, attending: true, sessions: workshop, member: member) expect(workshop.attendee? member).to be true login member visit workshop_path workshop expect(page).not_to have_button("Attend as a coach") expect(page).not_to have_button("Join the coach waiting list") expect(page).to have_text("You're attending this event") expect(page).to have_button("Cancel your attendance") end scenario "A logged-in user signed up on the coach attendance list can remove themselves from the event" do Fabricate(:coach_session_invitation, attending: true, sessions: workshop, member: member) expect(workshop.attendee? member).to be true login member visit workshop_path workshop click_button "Cancel your attendance" expect(current_path).to eq(removed_workshop_path workshop) expect(workshop.attendee? member).to be false expect(workshop.waitlisted? member).to be false end scenario "A logged-in user on the student waiting list sees that they're on the waiting list" do invite = Fabricate(:student_session_invitation, sessions: workshop, member: member) WaitingList.add(invite) expect(workshop.attendee? member).to be false expect(workshop.waitlisted? member).to be true login member visit workshop_path workshop expect(page).to have_content("You're on the waiting list") expect(page).to have_button("Leave the waiting list") end scenario "A logged-in user on the student waiting list can remove themself from the waiting list" do invite = Fabricate(:student_session_invitation, sessions: workshop, member: member) WaitingList.add(invite) expect(workshop.waitlisted? member).to be true login member visit workshop_path workshop click_button "Leave the waiting list" expect(current_path).to eq(removed_workshop_path workshop) expect(workshop.waitlisted? member).to be false end scenario "A logged-in user on the coach waiting list sees that they're on the waiting list" do invite = Fabricate(:coach_session_invitation, sessions: workshop, member: member) WaitingList.add(invite) expect(workshop.attendee? member).to be false expect(workshop.waitlisted? member).to be true login member visit workshop_path workshop expect(page).to have_content("You're on the waiting list") expect(page).to have_button("Leave the waiting list") end scenario "A logged-in user on the coach waiting list can remove themself from the waiting list" do invite = Fabricate(:coach_session_invitation, sessions: workshop, member: member) WaitingList.add(invite) expect(workshop.waitlisted? member).to be true login member visit workshop_path workshop click_button "Leave the waiting list" expect(current_path).to eq(removed_workshop_path workshop) expect(workshop.waitlisted? member).to be false end scenario "A user with both coach and student invites, waitlisted as a student, sees the student messaging on the waitlisted page" do invite = Fabricate(:student_session_invitation, sessions: workshop, member: member) Fabricate(:coach_session_invitation, sessions: workshop, member: member) WaitingList.add(invite) login member visit waitlisted_workshop_path workshop expect(page).not_to have_content("As a coach") expect(page).to have_content("As a student") end scenario "A user with both coach and student invites, waitlisted as a coach, sees the coach messaging on the waitlisted page" do Fabricate(:student_session_invitation, sessions: workshop, member: member) invite = Fabricate(:coach_session_invitation, sessions: workshop, member: member) WaitingList.add(invite) login member visit waitlisted_workshop_path workshop expect(page).to have_content("As a coach") expect(page).not_to have_content("As a student") end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Photo do let(:photo_object) { photo } let(:subject) { described_class.new(photo_object) } it 'should create a photo object' do expect(subject).to be_kind_of(Photo) end it 'should have an id attribute' do expect(subject.id).to be_truthy end it 'should have a url attribute' do expect(subject.url).to be_truthy end it 'should save the raw attribute' do expect(subject.raw).to eq photo_object end end
class StudentRecord < ApplicationRecord belongs_to :student validates :student_id, presence: true, uniqueness: true validates :student_number, presence: true, uniqueness: true def self.params_errors(params) params_errors = {} student_number = params[:student_number] if student_number.empty? params_errors[:student_number] = ["can't be blank"] elsif StudentRecord.exists?(student_number: student_number) params_errors[:student_number] = ["already exists"] end params_errors end def add_relavent_errors(student_errors) keys = [:student_number] keys.each do |k| if student_errors.messages[k] errors.messages[k] = [""] end end end end
#!/usr/bin/ruby # Calendar version = "1.0.0" # 2016-02-10 # # This script outputs a monthly calendar. # It's very configurable, and can produce CSS-ready HTML output, as well # as the more conventional monospaced calendar for the command-line. # # Made by Matt Gemmell - mattgemmell.com - @mattgemmell # github_url = "http://github.com/mattgemmell/Calendar" # # Requirements: just Ruby itself, and its standard library. # # How to use: # • Run the script on the command line for this month's calendar. # • Use the -h flag to see a list of available options. # Configuration defaults; can be overridden on command line and/or conf file. $startDayOfWeek = 0 # Sunday is 0. Max value is 6, for Saturday. $numDaysInWeek = 7 # might want to show only weekdays etc # == Everything below can be overridden in the configuration file. # Output formatting $space = " " # should be (at most) one character; will be trimmed to one char $newline = "\n" # should usually contain at least "\n" $weekdayHeadingNameLength = 3 $monthHeadingFormatString = "%B %Y" # Date.strftime $shortenMonthHeadingToFit = true # try shorter formats if necessary to fit # Layout (spaces horizontally, and lines vertically) $calendarPadding = {top: 1, bottom: 1, left: 1, right: 1, between: 1} # around entire calendar; "between" is between successive monthly calendars if showing multiple $calendarHeadingPadding = {top: 1, bottom: 1} # vertical padding above and below the row of weekday headings $cellSpacing = {horizontal: 1, vertical: 1} # between cells only, not at edges # Content wrapping $wrapCurrent = {before_day: "\033[7m", after_day: "\033[0;1m", before_week: "\033[1m", after_week: "\033[0m", before_month: "", after_month: ""} $currentConditionalMarker = {before: "CURRENT_BEFORE", after: "CURRENT_AFTER"} =begin Use the two "currentConditionalMarker" entries in the following "wrap…" hashes. When the calendar is being generated, in each case the markers will be replaced with the corresponding "wrapCurrent" entry, iff the day/week/month corresponds to the current date. This allows easy styling of today, this week, and this month. e.g. with the default values for wrapCurrent and currentConditionalMarker: wrapCalendar = {before: "<div class='monthCURRENT_BEFORE'>", after: "</div>"} will yield: <div class='month current'>…</div> for the current month, and: <div class='month'>…</div> for any other months. e.g. with these values instead: wrapCurrent = {before_day: "[", after_day: "]"} $wrapDay = {before: "CURRENT_BEFORE", after: "CURRENT_AFTER"} will yield something like: 1 2 [3] 4 5 if today is the 3rd day of the requested calendar month. =end $wrapOutput = {before: "", after: ""} # around entire output $wrapCalendar = {before: "CURRENT_BEFORE", after: "CURRENT_AFTER"} # around each monthly calendar $wrapMonthHeading = {before: "", after: ""} # around calendar month/year heading $wrapDateGrid = {before: "", after: ""} # includes weekday headings $wrapWeekdayHeadingsRow = {before: "", after: ""} # around entire weekday heading row $wrapWeekdayHeading = {before: "", after: ""} # around each weekday heading cell $wrapDaysGrid = {before: "", after: ""} # not including weekday headings $wrapDaysRow = {before: "CURRENT_BEFORE", after: "CURRENT_AFTER"} # around each entire row of days $wrapDay = {before: "CURRENT_BEFORE", after: "CURRENT_AFTER"} # around each individual day cell require 'date' def days_in_month(date = DateTime.now) # Return day-number of last day in month. Date.new(date.year, date.month, -1).day end def cellCharacterWidth return [2, $weekdayHeadingNameLength].max end def calendarCharacterWidth return (cellCharacterWidth() * $numDaysInWeek) + ($cellSpacing[:horizontal] * ($numDaysInWeek - 1)) end def month_calendar(month = nil, year = nil) firstOfMonthDate = nil if month == nil and year == nil today = DateTime.now month = today.month year = today.year elsif month == nil month = 1 elsif year == nil year = DateTime.now.year end if year < 0 year = 0 end if month < 1 month = 1 elsif month > 12 month = 12 end firstOfMonthDate = DateTime.new(year, month, 1) todayDate = DateTime.now monthIsCurrent = (todayDate.month == month and todayDate.year == year) output = "" # Sanitise some values if $startDayOfWeek < 0 $startDayOfWeek = $startDayOfWeek + 7 elsif $startDayOfWeek > 6 $startDayOfWeek = $startDayOfWeek - 7 end if $space.length > 1 $space = $space.slice(0, 1) end if $numDaysInWeek < 1 $numDaysInWeek = 1 elsif $numDaysInWeek > 7 $numDaysInWeek = 7 end # Calculate character-widths, not including calendar's overall padding. cellCharWidth = cellCharacterWidth() calendarCharWidth = calendarCharacterWidth() # Handle start-of-calendar wrapping. replacement = (monthIsCurrent ? $wrapCurrent[:before_month] : "") output = "#{output}#{$wrapCalendar[:before].gsub($currentConditionalMarker[:before], replacement)}" # Output padding before calendar for i in 1..$calendarPadding[:top] $calendarPadding[:left].times do output = "#{output}#{$space}" end calendarCharWidth.times do output = "#{output}#{$space}" end $calendarPadding[:right].times do output = "#{output}#{$space}" end output = "#{output}#{$newline}" end # Calendar month heading. if $monthHeadingFormatString.length > 0 monthHeading = firstOfMonthDate.strftime(format = $monthHeadingFormatString) $calendarPadding[:left].times do output = "#{output}#{$space}" end output = "#{output}#{$wrapMonthHeading[:before]}" numLeadingSpaces = (calendarCharWidth - monthHeading.length) / 2 if numLeadingSpaces >= 0 numLeadingSpaces.times do output = "#{output}#{$space}" end output = "#{output}#{monthHeading}" remainingSpaces = calendarCharWidth - monthHeading.length - numLeadingSpaces remainingSpaces.times do output = "#{output}#{$space}" end else if $shortenMonthHeadingToFit # Try some shorter variants of the heading. shorterHeadingFormats = Array["%b %Y", "%b %y", "%b"] shorterHeadingFormats.each do |thisFormat| shortMonthHeading = firstOfMonthDate.strftime(thisFormat) if shortMonthHeading.length <= calendarCharWidth numLeadingSpaces = (calendarCharWidth - shortMonthHeading.length) / 2 numLeadingSpaces.times do output = "#{output}#{$space}" end output = "#{output}#{shortMonthHeading}" remainingSpaces = calendarCharWidth - shortMonthHeading.length - numLeadingSpaces remainingSpaces.times do output = "#{output}#{$space}" end break end end else # Abbreviate month heading with an ellipsis. numAvailableChars = calendarCharWidth - 1 numLeadingChars = numAvailableChars.fdiv(2).ceil numTrailingChars = numAvailableChars - numLeadingChars output = "#{output}#{monthHeading.slice(0, numLeadingChars)}…#{monthHeading.slice(-numTrailingChars, numTrailingChars)}" end end output = "#{output}#{$wrapMonthHeading[:after]}" $calendarPadding[:right].times do output = "#{output}#{$space}" end output = "#{output}#{$newline}" # Padding between month heading and weekday headings for i in 1..$calendarHeadingPadding[:top] $calendarPadding[:left].times do output = "#{output}#{$space}" end calendarCharWidth.times do output = "#{output}#{$space}" end $calendarPadding[:right].times do output = "#{output}#{$space}" end output = "#{output}#{$newline}" end end output = "#{output}#{$wrapDateGrid[:before]}" # Weekday headings if $weekdayHeadingNameLength > 0 validWeekdays = Array.new monthHeading = firstOfMonthDate.strftime(format = $monthHeadingFormatString) $calendarPadding[:left].times do output = "#{output}#{$space}" end output = "#{output}#{$wrapWeekdayHeadingsRow[:before]}" # Output day headings right-aligned in available cell-width if narrower for i in 0..($numDaysInWeek - 1) weekdayNum = i + $startDayOfWeek if weekdayNum >= 7 weekdayNum -= 7 end validWeekdays.push(weekdayNum) # Weekday heading dayName = Date::DAYNAMES[weekdayNum].slice(0, $weekdayHeadingNameLength) if dayName.length < cellCharWidth numLeadingSpaces = cellCharWidth - dayName.length numLeadingSpaces.times do output = "#{output}#{$space}" end end output = "#{output}#{$wrapWeekdayHeading[:before]}" output = "#{output}#{dayName}" output = "#{output}#{$wrapWeekdayHeading[:after]}" if i < ($numDaysInWeek - 1) # Intercell horizontal separator $cellSpacing[:horizontal].times do output = "#{output}#{$space}" end end end output = "#{output}#{$wrapWeekdayHeadingsRow[:after]}" $calendarPadding[:right].times do output = "#{output}#{$space}" end output = "#{output}#{$newline}" # Padding between weekday headings and day grid for i in 1..$calendarHeadingPadding[:bottom] $calendarPadding[:left].times do output = "#{output}#{$space}" end calendarCharWidth.times do output = "#{output}#{$space}" end $calendarPadding[:right].times do output = "#{output}#{$space}" end output = "#{output}#{$newline}" end end output = "#{output}#{$wrapDaysGrid[:before]}" # Day grid rows, each (except last) with vertical cell spacing afterwards numDaysInMonth = days_in_month(firstOfMonthDate) startingWeekdayOfMonth = firstOfMonthDate.wday monthWeekStartOffset = ($startDayOfWeek - (startingWeekdayOfMonth + 7)) if monthWeekStartOffset < -6 monthWeekStartOffset = monthWeekStartOffset + 7 end currentDayNum = 1 + monthWeekStartOffset numRows = (numDaysInMonth - monthWeekStartOffset).fdiv(7).ceil numCells = numRows * $numDaysInWeek #puts "We're processing day #{firstOfMonthDate.day} of #{numDaysInMonth} in this month." #puts "We're starting weeks on a #{Date::DAYNAMES[$startDayOfWeek]} (weekday #{$startDayOfWeek}), and showing #{$numDaysInWeek} days per week." #puts "This month started on a \033[1m#{Date::DAYNAMES[startingWeekdayOfMonth]}\033[0m (weekday #{startingWeekdayOfMonth})." #puts "Offset of 1st of this month from starting day of week is #{monthWeekStartOffset}." #puts "Starting on effective day number #{currentDayNum}." #puts "We'll need #{numRows} rows, with a total of #{numCells} cells." # Adjust starting point if necessary. startingCellNum = 1 if monthWeekStartOffset.abs >= $numDaysInWeek startingCellNum = startingCellNum + $numDaysInWeek end lastRowStartEffectiveDay = 0 for i in startingCellNum..numCells # Work out correct currentDayNum (or blank space) to show for this cell. row = (i / $numDaysInWeek) + 1 if (i % $numDaysInWeek) == 0 row = row - 1 end col = (i % $numDaysInWeek) if col == 0 col = $numDaysInWeek end currentDayNum = col + monthWeekStartOffset + ((row - 1) * 7) effectiveDayNum = currentDayNum if col == 1 lastRowStartEffectiveDay = effectiveDayNum end if currentDayNum < 1 or currentDayNum > numDaysInMonth # This is a blank cell. currentDayNum = 0 end # Work out if this row/week and/or cell contains today. weekIsCurrent = false dayIsCurrent = false if monthIsCurrent if todayDate.day >= lastRowStartEffectiveDay and todayDate.day < lastRowStartEffectiveDay + 7 weekIsCurrent = true if todayDate.day == effectiveDayNum dayIsCurrent = true end end end # Decide if we need to start a row. if col == 1 $calendarPadding[:left].times do output = "#{output}#{$space}" end # Handle start-of-row wrapping. replacement = (weekIsCurrent ? $wrapCurrent[:before_week] : "") output = "#{output}#{$wrapDaysRow[:before].gsub($currentConditionalMarker[:before], replacement)}" end # Output either a blank cell or a day-number. cellContent = (currentDayNum == 0 ? "" : "#{currentDayNum}") #puts "cell #{i}, row #{row}, col #{col} [#{cellContent}]" if cellContent.length < cellCharWidth numLeadingSpaces = cellCharWidth - cellContent.length numLeadingSpaces.times do output = "#{output}#{$space}" end end # Handle start-of-day wrapping. replacement = (dayIsCurrent ? $wrapCurrent[:before_day] : "") output = "#{output}#{$wrapDay[:before].gsub($currentConditionalMarker[:before], replacement)}" # Output cell contents output = "#{output}#{cellContent}" # Handle end-of-day wrapping. replacement = (dayIsCurrent ? $wrapCurrent[:after_day] : "") output = "#{output}#{$wrapDay[:after].gsub($currentConditionalMarker[:after], replacement)}" # Output either horizontal cell-spacing or the end of a row. if col < $numDaysInWeek # Output horizontal cell-spacing $cellSpacing[:horizontal].times do output = "#{output}#{$space}" end else # Handle end-of-row wrapping. replacement = (weekIsCurrent ? $wrapCurrent[:after_week] : "") output = "#{output}#{$wrapDaysRow[:after].gsub($currentConditionalMarker[:after], replacement)}" # Output end of row padding and newline $calendarPadding[:right].times do output = "#{output}#{$space}" end output = "#{output}#{$newline}" # Decide whether to output vertical cell-spacing before the next row. if row < numRows # Output vertical cell-spacing for i in 1..$cellSpacing[:vertical] $calendarPadding[:left].times do output = "#{output}#{$space}" end calendarCharWidth.times do output = "#{output}#{$space}" end $calendarPadding[:right].times do output = "#{output}#{$space}" end output = "#{output}#{$newline}" end end end end output = "#{output}#{$wrapDaysGrid[:after]}" output = "#{output}#{$wrapDateGrid[:after]}" # Output padding after calendar for i in 1..$calendarPadding[:bottom] $calendarPadding[:left].times do output = "#{output}#{$space}" end calendarCharWidth.times do output = "#{output}#{$space}" end $calendarPadding[:right].times do output = "#{output}#{$space}" end output = "#{output}#{$newline}" end # Handle end-of-calendar wrapping. replacement = (monthIsCurrent ? $wrapCurrent[:after_month] : "") output = "#{output}#{$wrapCalendar[:after].gsub($currentConditionalMarker[:after], replacement)}" return output end def makeCalendars(months) output = "" interCalendarPadding = "" if months.count > 1 for i in 1..$calendarPadding[:between] $calendarPadding[:left].times do interCalendarPadding = "#{interCalendarPadding}#{$space}" end calendarCharacterWidth().times do interCalendarPadding = "#{interCalendarPadding}#{$space}" end $calendarPadding[:right].times do interCalendarPadding = "#{interCalendarPadding}#{$space}" end interCalendarPadding = "#{interCalendarPadding}#{$newline}" end end for i in 0..(months.count - 1) thisCalendar = month_calendar(months[i].month, months[i].year) output = "#{output}#{thisCalendar}" if i < (months.count - 1) output = "#{output}#{interCalendarPadding}" end end output = "#{$wrapOutput[:before]}#{output}#{$wrapOutput[:after]}" return output end # == End of functions == # Pay attention to any config options on the command line config_file = nil todayDate = DateTime.now monthNum = todayDate.month yearNum = todayDate.year monthOverridden = false yearOverridden = false startingWeekdayOverridden = false numDaysInWeekOverridden = false showSurroundingMonths = false require 'optparse' parser = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.on("-m n", "--month", OptionParser::DecimalInteger, "Shows a calendar for given month in current year (1 = January)") do |month| monthNum = month monthOverridden = true end opts.on("-y n", "--year", OptionParser::DecimalInteger, "With -m, chooses the year; otherwise shows every month of given year") do |year| yearNum = year yearOverridden = true end opts.on("-S", "--show-surrounding", "Also shows months before and after the specified month") do showSurroundingMonths = true end opts.on("-w n", "--starting-weekday", OptionParser::DecimalInteger, "Starts weeks on the given day (0 = Sunday)") do |startingWeekday| $startDayOfWeek = startingWeekday startingWeekdayOverridden = true end opts.on("-n n", "--days-per-week", OptionParser::DecimalInteger, "Sets the number of days per week to show") do |numDays| $numDaysInWeek = numDays numDaysInWeekOverridden = true end opts.on("-c file", "--config=file", "Use file as the configuration file") do |config| config_file = config end opts.on("-v", "--version", "Shows the version") do puts <<END #{$0} version #{version} ~ #{github_url} END exit end end parser.parse!(ARGV) # Load external config file if config_file != nil require "yaml" config = {} if File.exist?(config_file) config = YAML::load_file(config_file) if !config puts "Failed to load the config file \"#{config_file}\". Using default settings." end else puts "Couldn't find the config file \"#{config_file}\". Using default settings." end # Allow config file to override internal values if config if (config["startDayOfWeek"] and !startingWeekdayOverridden) $startDayOfWeek = config["startDayOfWeek"] end if (config["numDaysInWeek"] and !numDaysInWeekOverridden) $numDaysInWeek = config["numDaysInWeek"] end if (config["space"]) $space = config["space"] end if (config["newline"]) $newline = config["newline"] end if (config["weekdayHeadingNameLength"]) $weekdayHeadingNameLength = config["weekdayHeadingNameLength"] end if (config["monthHeadingFormatString"]) $monthHeadingFormatString = config["monthHeadingFormatString"] end if (config["shortenMonthHeadingToFit"]) $shortenMonthHeadingToFit = config["shortenMonthHeadingToFit"] end if (config["calendarPadding"]) $calendarPadding = config["calendarPadding"] end if (config["calendarHeadingPadding"]) $calendarHeadingPadding = config["calendarHeadingPadding"] end if (config["cellSpacing"]) $cellSpacing = config["cellSpacing"] end if (config["wrapCurrent"]) $wrapCurrent = config["wrapCurrent"] end if (config["currentConditionalMarker"]) $currentConditionalMarker = config["currentConditionalMarker"] end if (config["wrapOutput"]) $wrapOutput = config["wrapOutput"] end if (config["wrapCalendar"]) $wrapCalendar = config["wrapCalendar"] end if (config["wrapMonthHeading"]) $wrapMonthHeading = config["wrapMonthHeading"] end if (config["wrapDateGrid"]) $wrapDateGrid = config["wrapDateGrid"] end if (config["wrapWeekdayHeadingsRow"]) $wrapWeekdayHeadingsRow = config["wrapWeekdayHeadingsRow"] end if (config["wrapWeekdayHeading"]) $wrapWeekdayHeading = config["wrapWeekdayHeading"] end if (config["wrapDaysGrid"]) $wrapDaysGrid = config["wrapDaysGrid"] end if (config["wrapDaysRow"]) $wrapDaysRow = config["wrapDaysRow"] end if (config["wrapDay"]) $wrapDay = config["wrapDay"] end end end # Create appropriate calendar(s). monthDates = Array.new if yearOverridden and !monthOverridden # Show full year of monthly calendars. for i in 1..12 monthDates.push(DateTime.new(yearNum, i, 1)) end else # Show a single monthly calendar. theMonth = DateTime.new(yearNum, monthNum, 1) monthDates.push(theMonth) end # Deal with 'surrounding' flag. if showSurroundingMonths monthDates.unshift(monthDates.first.prev_month) monthDates.push(monthDates.last.next_month) end # Obtain and echo output. output = makeCalendars(monthDates) print output
$:.unshift File.expand_path("../lib", __FILE__) require "mengpaneel/version" Gem::Specification.new do |spec| spec.name = "mengpaneel" spec.version = Mengpaneel::VERSION spec.author = "Douwe Maan" spec.email = "douwe@selenight.nl" spec.summary = "Mengpaneel makes Mixpanel a breeze to use in Rails apps." spec.description = "Mengpaneel gives you a single way to interact with Mixpanel from your Rails controllers, with Mengpaneel taking it upon itself to make sure everything gets to Mixpanel." spec.homepage = "https://github.com/DouweM/mengpaneel" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.require_paths = ["lib"] spec.add_dependency "activesupport" spec.add_dependency "mixpanel-ruby" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" end
class Fabric < ActiveRecord::Base attr_accessible :color, :price, :quantity, :serial, :meters_sold, :rolls_sold, :total_profit has_many :records def self.repeated_serial?(serial_num) return !Fabric.where("serial=?", serial_num).blank? end def add_new_record(data_hash) # Get the date and use it to create a new record record = Record.new record.update_record(data_hash) self.records << record end end
Pakyow::App.bindings do scope :link do restful :link # TODO https://github.com/iamvery/pinster-pakyow/pull/7#issuecomment-197944275 binding :url do { href: bindable[:url], content: bindable[:url], } end end end
# # Cookbook Name:: hadoop_wrapper # Recipe:: default # # Copyright © 2013-2016 Cask Data, 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. # # We require Java, and the Hadoop cookbook doesn't have it as a dependency include_recipe 'java::default' if node.key?('java') && node['java'].key?('java_home') Chef::Log.info("JAVA_HOME = #{node['java']['java_home']}") # set in ruby environment for commands like hdfs namenode -format ENV['JAVA_HOME'] = node['java']['java_home'] # set in hadoop_env node.default['hadoop']['hadoop_env']['java_home'] = node['java']['java_home'] # set in hbase_env node.default['hbase']['hbase_env']['java_home'] = node['java']['java_home'] # set in hive_env node.default['hive']['hive_env']['java_home'] = node['java']['java_home'] end include_recipe 'hadoop::default' include_recipe 'hadoop_wrapper::kerberos_init'
class HappyHour < ActiveRecord::Base has_many :bargains, dependent: :destroy belongs_to :location attr_accessible :days, :end_time, :name, :start_time, :version, :record_number, :same_bargains scope :open_today, -> { where("days like '%#{self.todays_letter}%'") } def show_bargains if same_bargains begin Bargain.where('happy_hour_id = ?', same_bargains).all rescue ActiveRecord::RecordNotFound [ Bargain.new { |x| x.deal = "same_bargain is not valid happy hour id. Happy Hour not found" } ] end else bargains end end def self.todays_letter day_of_the_week = (Time.now - (60*60*7)).wday case day_of_the_week when 0 "U" #Sunday when 1 "M" #Monday when 2 "T" #Tuesday when 3 "W" #Wednesday when 4 "H" #Thursday when 5 "F" #Friday when 6 "S" #Saturday end end def open_now? open_today? && open_at_this_time? end def open_today? days.include?(HappyHour.todays_letter) # Will need to change to account for happy hours after midnight. end # It'll return false negatives when you're 12am+ on a day not # specifically listed in the days attribute def open_at_this_time? now = timenow time_inside?(now, start_time.utc, end_time.utc) end private # converts datetime object to float containing the time w/ minutes as decimals (e.g. 5:30 => 5.30) def t2f(time) time.strftime('%H.%M').to_f end def time_inside?(time, start, stop) if t2f(stop) < t2f(start) if t2f(time) >= t2f(start) t2f(time) >= t2f(stop) elsif t2f(time) <= t2f(start) t2f(time) <= t2f(stop) end else t2f(start) < t2f(time) && t2f(time) < t2f(stop) end end def timenow Time.now - (60*60*7) # utc to pdt offset, temporary. Also repeated up top, method doesn't work end end
require 'rails_helper' feature "user signs out" do before(:each) do @user = FactoryBot.create(:user) sign_in @user visit root_path click_on "sign out" end scenario "they see a flash message" do expect(page).to have_content("Signed out successfully") end scenario "they don't appear signed in" do user_doesnt_appear_signed_in("someone") end end
require 'uniform_notifier/base' require 'mysql2' class UniformNotifier class Mysql < Base @config = nil class << self def active? @config && mysql_client end def setup_connection(config = {}) @config = config create_table end protected # Bullet calls `out_of_channel_notify` with following parameter. # { # :user => whoami, # :url => url, # :title => title, # :body => body_with_caller, # } def _out_of_channel_notify(data) statement = mysql_client.prepare('INSERT INTO bullet_notifications(url, title, body, created_at) VALUES(?, ?, ?, ?)') statement.execute(data[:url], data[:title], data[:body], Time.now) end private def mysql_client @mysql2 ||= Mysql2::Client.new(@config) end def create_table mysql_client.query('DROP TABLE IF EXISTS bullet_notifications') mysql_client.query(<<-"SQL") CREATE TABLE bullet_notifications ( id int not null auto_increment, url varchar(255), title varchar(255), body text, created_at datetime, updated_at timestamp, primary key (id) ) SQL end end end end
require 'kfsdb' require 'csv' require 'json' Org = Struct.new(:chart, :org, :name, :type) OrgKey = Struct.new(:chart, :org) class OrgFinder def initialize @parents = {} @orgs = {} end def find_campus(chart, org, con) end def find_school(chart, org, con) end private def find_parent(chart, org, con) key = OrgKey.new(chart, org) if @parents.include?(key) @parents[key] else org = nil con.query("select fin_coa_cd, org_cd, org_nm, org_typ_cd from ca_org_t where RPTS_TO_FIN_COA_CD = ? and RPTS_TO_ORG_CD = ?", chart, org) do |row| org = Org.new(row["fin_coa_cd"], row["org_cd"], row["org_nm"], row["org_typ_cd"]) @parents[key] = org end org end end def find_org(chart, org, con) key = OrgKey.new(chart, org) if @orgs.include?(key) @orgs[key] else org = nil con.query("select org_nm, org_typ_cd from ca_org_t where fin_coa_cd = ? and org_cd = ?", chart, org) do |row| org = Org.new(chart, org, row["org_nm"], row["org_typ_cd"]) @orgs[key] = org end org end end end class PrincipalFinder def initialize @principals = {} end def find_principal_name(principal_id, con) if @principals.include?(principal_id) @principals[principal_id] else principal_name = "" con.query("select prncpl_nm from krim_prncpl_t where prncpl_id = ?",principal_id) do |row| principal_name = row["prncpl_nm"] @principals[principal_id] = principal_name end principal_name end end end def lookup_campus_and_college(fin_coa_cd, org_cd, con) end def lookup_basic_balance_info(con) query =<<-QUERY select distinct gl_balance_t.UNIV_FISCAL_YR, gl_balance_t.FIN_COA_CD, gl_balance_t.ACCOUNT_NBR, gl_balance_t.SUB_ACCT_NBR, ca_org_t.fin_coa_cd as org_fin_coa_cd, ca_org_t.org_cd, ca_org_t.org_nm, gl_balance_t.fin_obj_typ_cd, CA_OBJ_CONSOLDTN_T.FIN_COA_CD as cons_fin_coa_cd, CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_CD, CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_NM, ca_account_t.ACCT_FSC_OFC_UID, ca_account_t.ACCT_SPVSR_UNVL_ID, ca_account_t.ACCT_MGR_UNVL_ID, ca_org_t.ORG_MGR_UNVL_ID, ca_account_t.ACCT_CLOSED_IND, ca_obj_type_t.fin_obj_typ_nm, ca_acctg_ctgry_t.acctg_ctgry_desc, ca_sub_acct_t.sub_acct_nm, ca_sub_fund_grp_t.sub_fund_grp_cd, ca_fund_grp_t.fund_grp_cd, ca_fund_grp_t.fund_grp_nm from (ca_org_t join (ca_account_t join (CA_SUB_FUND_GRP_T join CA_FUND_GRP_T on CA_SUB_FUND_GRP_T.FUND_GRP_CD = CA_FUND_GRP_T.FUND_GRP_CD) on ca_account_t.SUB_FUND_GRP_CD = CA_SUB_FUND_GRP_T.SUB_FUND_GRP_CD) on ca_account_t.fin_coa_cd = ca_org_t.fin_coa_cd and ca_account_t.org_cd = ca_org_t.org_cd) join (((gl_balance_t join (ca_object_code_t join (CA_OBJ_LEVEL_T join CA_OBJ_CONSOLDTN_T on CA_OBJ_LEVEL_T.FIN_COA_CD = CA_OBJ_CONSOLDTN_T.FIN_COA_CD and CA_OBJ_LEVEL_T.FIN_CONS_OBJ_CD = CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_CD) on ca_object_code_t.FIN_OBJ_LEVEL_CD = CA_OBJ_LEVEL_T.fin_obj_level_cd and ca_object_code_t.fin_coa_cd = ca_obj_level_t.fin_coa_cd) on gl_balance_t.univ_fiscal_yr = ca_object_code_t.univ_fiscal_yr and gl_balance_t.fin_coa_cd = ca_object_code_t.fin_coa_cd and gl_balance_t.fin_object_cd = ca_object_code_t.fin_object_cd) left join ca_sub_acct_t on gl_balance_t.fin_coa_cd = ca_sub_acct_t.fin_coa_cd and gl_balance_t.account_nbr = ca_sub_acct_t.account_nbr and gl_balance_t.sub_acct_nbr = ca_sub_acct_t.sub_acct_nbr) join (ca_obj_type_t join ca_acctg_ctgry_t on ca_obj_type_t.acctg_ctgry_cd = ca_acctg_ctgry_t.acctg_ctgry_cd) on gl_balance_t.fin_obj_typ_cd = ca_obj_type_t.fin_obj_typ_cd) on ca_account_t.fin_coa_cd = gl_balance_t.fin_coa_cd and ca_account_t.account_nbr = gl_balance_t.account_nbr --where gl_balance_t.univ_fiscal_yr = 2015 and ca_acctg_ctgry_t.acctg_ctgry_cd in ('IN','EX') where ca_acctg_ctgry_t.acctg_ctgry_cd in ('IN','EX') QUERY recs = [] con.query(query) do |row| column_names = row.columns.collect{|col| col.name} rec = row.to_hash recs << rec end recs end def update_principals(rec, principal_finder, rice_con) rec["fiscal_officer_principal_name"] = principal_finder.find_principal_name(rec.delete("acct_fsc_ofc_uid"),rice_con) rec["account_supervisor_principal_name"] = principal_finder.find_principal_name(rec.delete("acct_spvsr_unvl_id"),rice_con) rec["account_manager_principal_name"] = principal_finder.find_principal_name(rec.delete("acct_mgr_unvl_id"),rice_con) rec["organization_manager_principal_name"] = principal_finder.find_principal_name(rec.delete("org_mgr_unvl_id"),rice_con) end def clean_amount(amount) if amount.nil? amount = 0.0 else amount = amount.to_f end end def update_by_base_balance(balance_info, con) bb_query =<<-BBQUERY select sum(gl_balance_t.FIN_BEG_BAL_LN_AMT) as original_budget, sum(gl_balance_t.ACLN_ANNL_BAL_AMT) as base_budget from gl_balance_t join (ca_object_code_t join (CA_OBJ_LEVEL_T join CA_OBJ_CONSOLDTN_T on CA_OBJ_LEVEL_T.FIN_COA_CD = CA_OBJ_CONSOLDTN_T.FIN_COA_CD and CA_OBJ_LEVEL_T.FIN_CONS_OBJ_CD = CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_CD) on ca_object_code_t.FIN_OBJ_LEVEL_CD = CA_OBJ_LEVEL_T.fin_obj_level_cd and ca_object_code_t.fin_coa_cd = ca_obj_level_t.fin_coa_cd) on gl_balance_t.univ_fiscal_yr = ca_object_code_t.univ_fiscal_yr and gl_balance_t.fin_coa_cd = ca_object_code_t.fin_coa_cd and gl_balance_t.fin_object_cd = ca_object_code_t.fin_object_cd where gl_balance_t.univ_fiscal_yr = ? and gl_balance_t.fin_coa_cd = ? and gl_balance_t.account_nbr = ? and gl_balance_t.sub_acct_nbr = ? and ca_obj_consoldtn_t.fin_cons_obj_cd = ? and gl_balance_t.fin_balance_typ_cd = 'BB' BBQUERY con.query(bb_query, balance_info["univ_fiscal_yr"], balance_info["fin_coa_cd"], balance_info["account_nbr"], balance_info["sub_acct_nbr"], balance_info["fin_cons_obj_cd"]) do |row| balance_info["original_budget"] = row["original_budget"] balance_info["base_budget"] = row["base_budget"] end balance_info["original_budget"] = clean_amount(balance_info["original_budget"]) balance_info["base_budget"] = clean_amount(balance_info["base_budget"]) end def update_by_current_balance(balance_info, con) cb_query = <<-CBQUERY select sum(gl_balance_t.ACLN_ANNL_BAL_AMT) as current_budget from gl_balance_t join (ca_object_code_t join (CA_OBJ_LEVEL_T join CA_OBJ_CONSOLDTN_T on CA_OBJ_LEVEL_T.FIN_COA_CD = CA_OBJ_CONSOLDTN_T.FIN_COA_CD and CA_OBJ_LEVEL_T.FIN_CONS_OBJ_CD = CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_CD) on ca_object_code_t.FIN_OBJ_LEVEL_CD = CA_OBJ_LEVEL_T.fin_obj_level_cd and ca_object_code_t.fin_coa_cd = ca_obj_level_t.fin_coa_cd) on gl_balance_t.univ_fiscal_yr = ca_object_code_t.univ_fiscal_yr and gl_balance_t.fin_coa_cd = ca_object_code_t.fin_coa_cd and gl_balance_t.fin_object_cd = ca_object_code_t.fin_object_cd where gl_balance_t.univ_fiscal_yr = ? and gl_balance_t.fin_coa_cd = ? and gl_balance_t.account_nbr = ? and gl_balance_t.sub_acct_nbr = ? and ca_obj_consoldtn_t.fin_cons_obj_cd = ? and gl_balance_t.fin_balance_typ_cd = 'CB' CBQUERY con.query(cb_query, balance_info["univ_fiscal_yr"], balance_info["fin_coa_cd"], balance_info["account_nbr"], balance_info["sub_acct_nbr"], balance_info["fin_cons_obj_cd"]) do |row| balance_info["current_budget"] = row["current_budget"] end balance_info["current_budget"] = clean_amount(balance_info["current_budget"]) end def update_by_open_encumbrance(balance_info, con) en_query = <<-ENQUERY select sum(gl_balance_t.ACLN_ANNL_BAL_AMT) as open_encumbrances from gl_balance_t join (ca_object_code_t join (CA_OBJ_LEVEL_T join CA_OBJ_CONSOLDTN_T on CA_OBJ_LEVEL_T.FIN_COA_CD = CA_OBJ_CONSOLDTN_T.FIN_COA_CD and CA_OBJ_LEVEL_T.FIN_CONS_OBJ_CD = CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_CD) on ca_object_code_t.FIN_OBJ_LEVEL_CD = CA_OBJ_LEVEL_T.fin_obj_level_cd and ca_object_code_t.fin_coa_cd = ca_obj_level_t.fin_coa_cd) on gl_balance_t.univ_fiscal_yr = ca_object_code_t.univ_fiscal_yr and gl_balance_t.fin_coa_cd = ca_object_code_t.fin_coa_cd and gl_balance_t.fin_object_cd = ca_object_code_t.fin_object_cd where gl_balance_t.univ_fiscal_yr = ? and gl_balance_t.fin_coa_cd = ? and gl_balance_t.account_nbr = ? and gl_balance_t.sub_acct_nbr = ? and ca_obj_consoldtn_t.fin_cons_obj_cd = ? and gl_balance_t.fin_balance_typ_cd in ('EX','IE','CE') ENQUERY con.query(en_query, balance_info["univ_fiscal_yr"], balance_info["fin_coa_cd"], balance_info["account_nbr"], balance_info["sub_acct_nbr"], balance_info["fin_cons_obj_cd"]) do |row| balance_info["open_encumbrances"] = row["open_encumbrances"] end balance_info["open_encumbrances"] = clean_amount(balance_info["open_encumbrances"]) end def update_by_pre_encumbrance(balance_info, con) pe_query = <<-PEQUERY select sum(gl_balance_t.ACLN_ANNL_BAL_AMT) as pre_encumbrance from gl_balance_t join (ca_object_code_t join (CA_OBJ_LEVEL_T join CA_OBJ_CONSOLDTN_T on CA_OBJ_LEVEL_T.FIN_COA_CD = CA_OBJ_CONSOLDTN_T.FIN_COA_CD and CA_OBJ_LEVEL_T.FIN_CONS_OBJ_CD = CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_CD) on ca_object_code_t.FIN_OBJ_LEVEL_CD = CA_OBJ_LEVEL_T.fin_obj_level_cd and ca_object_code_t.fin_coa_cd = ca_obj_level_t.fin_coa_cd) on gl_balance_t.univ_fiscal_yr = ca_object_code_t.univ_fiscal_yr and gl_balance_t.fin_coa_cd = ca_object_code_t.fin_coa_cd and gl_balance_t.fin_object_cd = ca_object_code_t.fin_object_cd where gl_balance_t.univ_fiscal_yr = ? and gl_balance_t.fin_coa_cd = ? and gl_balance_t.account_nbr = ? and gl_balance_t.sub_acct_nbr = ? and ca_obj_consoldtn_t.fin_cons_obj_cd = ? and gl_balance_t.fin_balance_typ_cd = 'PE' PEQUERY con.query(pe_query, balance_info["univ_fiscal_yr"], balance_info["fin_coa_cd"], balance_info["account_nbr"], balance_info["sub_acct_nbr"], balance_info["fin_cons_obj_cd"]) do |row| balance_info["pre_encumbrance"] = row["pre_encumbrance"] end balance_info["pre_encumbrance"] = clean_amount(balance_info["pre_encumbrance"]) end def update_by_actual(balance_info, con) ac_query = <<-ACQUERY select sum(CONTR_GR_BB_AC_AMT + ACLN_ANNL_BAL_AMT) as inception_to_date, sum(ACLN_ANNL_BAL_AMT) as fiscal_year_total from gl_balance_t join (ca_object_code_t join (CA_OBJ_LEVEL_T join CA_OBJ_CONSOLDTN_T on CA_OBJ_LEVEL_T.FIN_COA_CD = CA_OBJ_CONSOLDTN_T.FIN_COA_CD and CA_OBJ_LEVEL_T.FIN_CONS_OBJ_CD = CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_CD) on ca_object_code_t.FIN_OBJ_LEVEL_CD = CA_OBJ_LEVEL_T.fin_obj_level_cd and ca_object_code_t.fin_coa_cd = ca_obj_level_t.fin_coa_cd) on gl_balance_t.univ_fiscal_yr = ca_object_code_t.univ_fiscal_yr and gl_balance_t.fin_coa_cd = ca_object_code_t.fin_coa_cd and gl_balance_t.fin_object_cd = ca_object_code_t.fin_object_cd where gl_balance_t.univ_fiscal_yr = ? and gl_balance_t.fin_coa_cd = ? and gl_balance_t.account_nbr = ? and gl_balance_t.sub_acct_nbr = ? and ca_obj_consoldtn_t.fin_cons_obj_cd = ? and gl_balance_t.fin_balance_typ_cd = 'AC' ACQUERY con.query(ac_query, balance_info["univ_fiscal_yr"], balance_info["fin_coa_cd"], balance_info["account_nbr"], balance_info["sub_acct_nbr"], balance_info["fin_cons_obj_cd"]) do |row| balance_info["inception_to_date"] = row["inception_to_date"] balance_info["fiscal_year_total"] = row["fiscal_year_total"] end balance_info["inception_to_date"] = clean_amount(balance_info["inception_to_date"]) balance_info["fiscal_year_actuals"] = clean_amount(balance_info["fiscal_year_actuals"]) balance_info["balance_available"] = balance_info["current_budget"] - balance_info["inception_to_date"] - balance_info["open_encumbrances"] - balance_info["pre_encumbrance"] balance_info["balance_available"] = clean_amount(balance_info["balance_available"]) end def build_period_records(balance_info, con) per_query = <<-PERQUERY select sum(MO1_ACCT_LN_AMT) as per1, sum(MO2_ACCT_LN_AMT) as per2, sum(MO3_ACCT_LN_AMT) as per3, sum(MO4_ACCT_LN_AMT) as per4, sum(MO4_ACCT_LN_AMT) as per4, sum(MO5_ACCT_LN_AMT) as per5, sum(MO6_ACCT_LN_AMT) as per6, sum(MO7_ACCT_LN_AMT) as per7, sum(MO8_ACCT_LN_AMT) as per8, sum(MO9_ACCT_LN_AMT) as per9, sum(MO10_ACCT_LN_AMT) as per10, sum(MO11_ACCT_LN_AMT) as per11, sum(MO12_ACCT_LN_AMT) as per12, sum(MO13_ACCT_LN_AMT) as per13 from gl_balance_t join (ca_object_code_t join (CA_OBJ_LEVEL_T join CA_OBJ_CONSOLDTN_T on CA_OBJ_LEVEL_T.FIN_COA_CD = CA_OBJ_CONSOLDTN_T.FIN_COA_CD and CA_OBJ_LEVEL_T.FIN_CONS_OBJ_CD = CA_OBJ_CONSOLDTN_T.FIN_CONS_OBJ_CD) on ca_object_code_t.FIN_OBJ_LEVEL_CD = CA_OBJ_LEVEL_T.fin_obj_level_cd and ca_object_code_t.fin_coa_cd = ca_obj_level_t.fin_coa_cd) on gl_balance_t.univ_fiscal_yr = ca_object_code_t.univ_fiscal_yr and gl_balance_t.fin_coa_cd = ca_object_code_t.fin_coa_cd and gl_balance_t.fin_object_cd = ca_object_code_t.fin_object_cd where gl_balance_t.univ_fiscal_yr = ? and gl_balance_t.fin_coa_cd = ? and gl_balance_t.account_nbr = ? and gl_balance_t.sub_acct_nbr = ? and ca_obj_consoldtn_t.fin_cons_obj_cd = ? and gl_balance_t.fin_balance_typ_cd = 'AC' PERQUERY per1 = 0.0 per2 = 0.0 per3 = 0.0 per4 = 0.0 per5 = 0.0 per6 = 0.0 per7 = 0.0 per8 = 0.0 per9 = 0.0 per10 = 0.0 per11 = 0.0 per12 = 0.0 per13 = 0.0 con.query(per_query, balance_info["univ_fiscal_yr"], balance_info["fin_coa_cd"], balance_info["account_nbr"], balance_info["sub_acct_nbr"], balance_info["fin_cons_obj_cd"]) do |row| per1 = clean_amount(row["per1"]) per2 = clean_amount(row["per2"]) per3 = clean_amount(row["per3"]) per4 = clean_amount(row["per4"]) per5 = clean_amount(row["per5"]) per6 = clean_amount(row["per6"]) per7 = clean_amount(row["per7"]) per8 = clean_amount(row["per8"]) per9 = clean_amount(row["per9"]) per10 = clean_amount(row["per10"]) per11 = clean_amount(row["per11"]) per12 = clean_amount(row["per12"]) per13 = clean_amount(row["per13"]) end bal_periods = [] bal_period1 = balance_info.clone bal_period1["current_month_actuals"] = per1 bal_period1["fiscal_year_actuals"] = per1 bal_periods << bal_period1 bal_period2 = balance_info.clone bal_period2["current_month_actuals"] = per2 bal_period2["fiscal_year_actuals"] = per1 + per2 bal_periods << bal_period2 bal_period3 = balance_info.clone bal_period3["current_month_actuals"] = per3 bal_period3["fiscal_year_actuals"] = per1 + per2 + per3 bal_periods << bal_period3 bal_period4 = balance_info.clone bal_period4["current_month_actuals"] = per4 bal_period4["fiscal_year_actuals"] = per1 + per2 + per3 + per4 bal_periods << bal_period4 bal_period5 = balance_info.clone bal_period5["current_month_actuals"] = per5 bal_period5["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 bal_periods << bal_period5 bal_period6 = balance_info.clone bal_period6["current_month_actuals"] = per6 bal_period6["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 + per6 bal_periods << bal_period6 bal_period7 = balance_info.clone bal_period7["current_month_actuals"] = per7 bal_period7["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 + per6 + per7 bal_periods << bal_period7 bal_period8 = balance_info.clone bal_period8["current_month_actuals"] = per8 bal_period8["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 + per6 + per7 + per8 bal_periods << bal_period8 bal_period9 = balance_info.clone bal_period9["current_month_actuals"] = per9 bal_period9["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 + per6 + per7 + per8 + per9 bal_periods << bal_period9 bal_period10 = balance_info.clone bal_period10["current_month_actuals"] = per10 bal_period10["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 + per6 + per7 + per8 + per9 + per10 bal_periods << bal_period10 bal_period11 = balance_info.clone bal_period11["current_month_actuals"] = per11 bal_period11["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 + per6 + per7 + per8 + per9 + per10 + per11 bal_periods << bal_period11 bal_period12 = balance_info.clone bal_period12["current_month_actuals"] = per12 bal_period12["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 + per6 + per7 + per8 + per9 + per10 + per11 + per12 bal_periods << bal_period12 bal_period13 = balance_info.clone bal_period13["current_month_actuals"] = per13 bal_period13["fiscal_year_actuals"] = per1 + per2 + per3 + per4 + per5 + per6 + per7 + per8 + per9 + per10 + per11 + per12 + per13 bal_periods << bal_period13 bal_periods end balance_periods = [] db_connect("kfstst_at_kfsstg") do |con| balance_infos = lookup_basic_balance_info(con) principal_finder = PrincipalFinder.new() db_connect("ricetst_at_kfsstg") do |rice_con| balance_infos.each {|balance_info| update_principals(balance_info, principal_finder, rice_con) } end balance_infos.each do |balance_info| update_by_base_balance(balance_info, con) update_by_current_balance(balance_info, con) update_by_open_encumbrance(balance_info, con) update_by_pre_encumbrance(balance_info, con) update_by_actual(balance_info, con) end balance_infos.each do |balance_info| balance_periods_for_info = build_period_records(balance_info, con) #puts "balance periods #{balance_periods.size} balance periods for info #{balance_periods_for_info.size}" balance_periods = balance_periods + balance_periods_for_info end end File.open("income_expense.json","w") do |fout| es_commands = (1..(balance_periods.size)).inject([]) do |commands, count| rec_info = {} rec_info["_index"] = "income_expense" rec_info["_type"] = "consolidated_balance" rec_info["_id"] = count.to_s command = {} command["create"] = rec_info commands << command commands end bulk_commands = es_commands.zip(balance_periods).flatten! bulk_commands.each do |rec| fout.write(JSON.generate(rec)+"\n") end end #col_names = balance_periods[0].keys #CSV.open("income_expense.csv","wb") do |csv| # csv << col_names # balance_periods.each do |rec| # values = col_names.inject([]) {|memo, value| memo << rec[value]} # csv << values # end #end
require 'test_helper' class MatchesControllerTest < ActionDispatch::IntegrationTest setup do @match = matches(:one) end test "should get index" do get matches_url, as: :json assert_response :success end test "should create match" do assert_difference('Match.count') do post matches_url, params: { match: { city: @match.city, date: @match.date, dl_applied: @match.dl_applied, id: @match.id, player_of_match: @match.player_of_match, result: @match.result, season: @match.season, team1: @match.team1, team2: @match.team2, toss_decision: @match.toss_decision, toss_winner: @match.toss_winner, umpire1: @match.umpire1, umpire2: @match.umpire2, umpire3: @match.umpire3, venue: @match.venue, win_by_runs: @match.win_by_runs, win_by_wickets: @match.win_by_wickets, winner: @match.winner } }, as: :json end assert_response 201 end test "should show match" do get match_url(@match), as: :json assert_response :success end test "should update match" do patch match_url(@match), params: { match: { city: @match.city, date: @match.date, dl_applied: @match.dl_applied, id: @match.id, player_of_match: @match.player_of_match, result: @match.result, season: @match.season, team1: @match.team1, team2: @match.team2, toss_decision: @match.toss_decision, toss_winner: @match.toss_winner, umpire1: @match.umpire1, umpire2: @match.umpire2, umpire3: @match.umpire3, venue: @match.venue, win_by_runs: @match.win_by_runs, win_by_wickets: @match.win_by_wickets, winner: @match.winner } }, as: :json assert_response 200 end test "should destroy match" do assert_difference('Match.count', -1) do delete match_url(@match), as: :json end assert_response 204 end end
class Gallery < ActiveRecord::Base attr_accessible :experiment_id, :picture_id, :tool_id validates :picture_id, presence: true belongs_to :experiment, class_name: 'Experiment' belongs_to :tool, class_name: 'Tool' belongs_to :picture, class_name: 'Picture' end
class CallRoute < ActiveRecord::Base # https://github.com/rails/strong_parameters include ActiveModel::ForbiddenAttributesProtection ROUTING_TABLES = ['prerouting', 'outbound', 'inbound', 'dtmf'] has_many :route_elements, :dependent => :destroy, :order => :position validates :name, :presence => true validates :routing_table, :presence => true, :inclusion => { :in => ROUTING_TABLES } acts_as_list :scope => '`routing_table` = \'#{routing_table}\'' after_save :create_elements def to_s name.to_s end def move_up? return self.position.to_i > CallRoute.where(:routing_table => self.routing_table ).order(:position).first.position.to_i end def move_down? return self.position.to_i < CallRoute.where(:routing_table => self.routing_table ).order(:position).last.position.to_i end def self.factory_defaults_prerouting(country_code, national_prefix = '', international_prefix = '', trunk_access_code = '', area_code = '') CallRoute.where(:routing_table => "prerouting").destroy_all CallRoute.create_prerouting_entry('international call', [ { :pattern => '^'+trunk_access_code+international_prefix+'([1-9]%d+)$', :replacement => '+%1', }, ], 'phonenumber') CallRoute.create_prerouting_entry('national call', [ { :pattern => '^'+trunk_access_code+national_prefix+'([1-9]%d+)$', :replacement => '+'+country_code+'%1', }, ], 'phonenumber') if !trunk_access_code.blank? && !area_code.blank? CallRoute.create_prerouting_entry('local call', [ { :pattern => '^'+trunk_access_code+'([1-9]%d+)$', :replacement => '+'+country_code+area_code+'%1', }, ], 'phonenumber') end CallRoute.create_prerouting_entry('log in', [ { :pattern => '^%*0%*$', :replacement => 'f-li', }, { :pattern => '^%*0%*(%+?%d+)#*$', :replacement => 'f-li-%1', }, { :pattern => '^%*0%*(%+?%d+)%*(%d+)#*$', :replacement => 'f-li-%1-%2', }, ]) CallRoute.create_prerouting_entry('log out', [ { :pattern => '^#0#$', :replacement => 'f-lo', }, ]) CallRoute.create_prerouting_entry('toggle ACD membership', [ { :pattern => '^%*5%*(%+?%d+)#$', :replacement => 'f-acdmtg-0-%1', }, ]) CallRoute.create_prerouting_entry('activate CLIP', [ { :pattern => '^%*30#$', :replacement => 'f-clipon', }, ]) CallRoute.create_prerouting_entry('deactivate CLIP', [ { :pattern => '^#30#$', :replacement => 'f-clipoff', }, ]) CallRoute.create_prerouting_entry('activate CLIR', [ { :pattern => '^#31#$', :replacement => 'f-cliron', }, ]) CallRoute.create_prerouting_entry('deactivate CLIR', [ { :pattern => '^%*31#$', :replacement => 'f-cliroff', }, ]) elements = [ { :pattern => '^#31#(%+?[1-9]%d+)$', :replacement => 'f-dcliron-%1', }, { :pattern => '^#31#'+trunk_access_code+international_prefix+'([1-9]%d+)$', :replacement => 'f-dcliron-+%1' }, { :pattern => '^#31#'+trunk_access_code+national_prefix+'([1-9]%d+)$', :replacement => 'f-dcliron-+'+country_code+'%1' }, ] if !trunk_access_code.blank? && !area_code.blank? elements << { :pattern => '^#31#'+trunk_access_code+'([1-9]%d+)$', :replacement => 'f-dcliron-+'+country_code+area_code+'%1' } end CallRoute.create_prerouting_entry('activate CLIR for call', elements) elements = [ { :pattern => '^%*31#(%+?[1-9]%d+)$', :replacement => 'f-dcliroff-%1', }, { :pattern => '^%*31#'+trunk_access_code+international_prefix+'([1-9]%d+)$', :replacement => 'f-dcliroff-+%1' }, { :pattern => '^%*31#'+trunk_access_code+national_prefix+'([1-9]%d+)$', :replacement => 'f-dcliroff-+'+country_code+'%1' }, ] if !trunk_access_code.blank? && !area_code.blank? elements << { :pattern => '^%*31#'+trunk_access_code+'([1-9]%d+)$', :replacement => 'f-dcliroff-+'+country_code+area_code+'%1' } end CallRoute.create_prerouting_entry('deactivate CLIR for call', elements) CallRoute.create_prerouting_entry('activate call waiting', [ { :pattern => '^%*43#$', :replacement => 'f-cwaon', }, ]) CallRoute.create_prerouting_entry('deactivate call waiting', [ { :pattern => '^#43#$', :replacement => 'f-cwaoff', }, ]) CallRoute.create_prerouting_entry('deactivate all call forwards', [ { :pattern => '^#002#$', :replacement => 'f-cfoff', }, ]) CallRoute.create_prerouting_entry('delete all call forwards', [ { :pattern => '^##002#$', :replacement => 'f-cfdel', }, ]) elements = [ { :pattern => '^%*21#$', :replacement => 'f-cfu', }, { :pattern => '^%*%*?21%*(%+?[1-9]%d+)#$', :replacement => 'f-cfu-%1', }, { :pattern => '^%*%*?21%*'+trunk_access_code+international_prefix+'([1-9]%d+)#$', :replacement => 'f-cfu-+%1', }, { :pattern => '^%*%*?21%*'+trunk_access_code+national_prefix+'([1-9]%d+)#$', :replacement => 'f-cfu-+'+country_code+'%1', }, ] if !trunk_access_code.blank? && !area_code.blank? elements << { :pattern => '^%*%*?21%*'+trunk_access_code+'([1-9]%d+)#$', :replacement => 'f-cfu-+'+country_code+area_code+'%1' } end CallRoute.create_prerouting_entry('set unconditional call forwarding', elements) CallRoute.create_prerouting_entry('deactivate unconditional call forwarding', [ { :pattern => '^#21#$', :replacement => 'f-cfuoff', }, ]) CallRoute.create_prerouting_entry('delete unconditional call forwarding', [ { :pattern => '^##21#$', :replacement => 'f-cfudel', }, ]) elements = [ { :pattern => '^%*61#$', :replacement => 'f-cfn', }, { :pattern => '^%*%*?61%*'+trunk_access_code+international_prefix+'([1-9]%d+)#$', :replacement => 'f-cfn-+%1', }, { :pattern => '^%*%*?61%*'+trunk_access_code+national_prefix+'([1-9]%d+)#$', :replacement => 'f-cfn-+'+country_code+'%1', }, { :pattern => '^%*%*?61%*(%+?[1-9]%d+)#$', :replacement => 'f-cfn-%1', }, { :pattern => '^%*%*?61%*'+trunk_access_code+international_prefix+'([1-9]%d+)%*(%d+)#$', :replacement => 'f-cfn-+%1-%2', }, { :pattern => '^%*%*?61%*'+trunk_access_code+national_prefix+'([1-9]%d+)%*(%d+)#$', :replacement => 'f-cfn-+'+country_code+'%1-%2', }, { :pattern => '^%*%*?61%*(%+?[1-9]%d+)%*(%d+)#$', :replacement => 'f-cfn-%1-%2', }, ] if !trunk_access_code.blank? && !area_code.blank? elements << { :pattern => '^%*%*?61%*'+trunk_access_code+'([1-9]%d+)#$', :replacement => 'f-cfn-+'+country_code+area_code+'%1' } elements << { :pattern => '^%*%*?61%*'+trunk_access_code+'([1-9]%d+)%*(%d+)#$', :replacement => 'f-cfn-+'+country_code+area_code+'%1-%2' } end CallRoute.create_prerouting_entry('call forward if not answered', elements) CallRoute.create_prerouting_entry('deactivate call forward if not answered', [ { :pattern => '^#61#$', :replacement => 'f-cfnoff', }, ]) CallRoute.create_prerouting_entry('delete call forward if not answered', [ { :pattern => '^##61#$', :replacement => 'f-cfndel', }, ]) elements = [ { :pattern => '^%*62#$', :replacement => 'f-cfo', }, { :pattern => '^%*%*?62%*(%+?[1-9]%d+)#$', :replacement => 'f-cfo-%1', }, { :pattern => '^%*%*?62%*'+trunk_access_code+international_prefix+'([1-9]%d+)#$', :replacement => 'f-cfo-+%1', }, { :pattern => '^%*%*?62%*'+trunk_access_code+national_prefix+'([1-9]%d+)#$', :replacement => 'f-cfo-+'+country_code+'%1', }, ] if !trunk_access_code.blank? && !area_code.blank? elements << { :pattern => '^%*%*?62%*'+trunk_access_code+'([1-9]%d+)#$', :replacement => 'f-cfo-+'+country_code+area_code+'%1' } end CallRoute.create_prerouting_entry('call forward if offline', elements) CallRoute.create_prerouting_entry('deactivate call forward if offline', [ { :pattern => '^#62#$', :replacement => 'f-cfooff', }, ]) CallRoute.create_prerouting_entry('delete call forward if offline', [ { :pattern => '^##62#$', :replacement => 'f-cfodel', }, ]) elements = [ { :pattern => '^%*67#$', :replacement => 'f-cfb', }, { :pattern => '^%*%*?67%*(%+?[1-9]%d+)#$', :replacement => 'f-cfb-%1', }, { :pattern => '^%*%*?67%*'+trunk_access_code+international_prefix+'([1-9]%d+)#$', :replacement => 'f-cfb-+%1', }, { :pattern => '^%*%*?67%*'+trunk_access_code+national_prefix+'([1-9]%d+)#$', :replacement => 'f-cfb-+'+country_code+'%1', }, ] if !trunk_access_code.blank? && !area_code.blank? elements << { :pattern => '^%*%*?67%*'+trunk_access_code+'([1-9]%d+)#$', :replacement => 'f-cfb-+'+country_code+area_code+'%1' } end CallRoute.create_prerouting_entry('call forward if busy', elements) CallRoute.create_prerouting_entry('deactivate call forward if busy', [ { :pattern => '^#67#$', :replacement => 'f-cfboff', }, ]) CallRoute.create_prerouting_entry('delete call forward if busy', [ { :pattern => '^##67#$', :replacement => 'f-cfbdel', }, ]) CallRoute.create_prerouting_entry('redial', [ { :pattern => '^%*66#$', :replacement => 'f-redial', }, ]) CallRoute.create_prerouting_entry('check voicemail', [ { :pattern => '^%*98$', :replacement => 'f-vmcheck', }, { :pattern => '^%*98#$', :replacement => 'f-vmcheck', }, { :pattern => '^%*98%*(%+?%d+)#$', :replacement => 'f-vmcheck-%1', }, ]) CallRoute.create_prerouting_entry('acivate auto logout', [ { :pattern => '^%*1337%*1%*1#$', :replacement => 'f-loaon', }, ]) CallRoute.create_prerouting_entry('deacivate auto logout', [ { :pattern => '^%*1337%*1%*0#$', :replacement => 'f-loaoff', }, ]) end def self.create_prerouting_entry(name, elements, endpoint_type = 'dialplanfunction') call_route = CallRoute.create(:routing_table => 'prerouting', :name => name, :endpoint_type => endpoint_type) if !call_route.errors.any? then elements.each do |element| call_route.route_elements.create( :var_in => 'destination_number', :var_out => 'destination_number', :pattern => element[:pattern], :replacement => element[:replacement], :action => 'match', :mandatory => false ) end end end def endpoint_str "#{endpoint_type}=#{endpoint_id}" end def endpoint if self.endpoint_id.to_i > 0 begin return self.endpoint_type.camelize.constantize.where(:id => self.endpoint_id.to_i).first rescue return nil end end end def xml @xml end def xml=(xml_string) @xml = xml_string if xml_string.blank? return end begin route_hash = Hash.from_xml(xml_string) rescue Exception => e errors.add(:xml, e.message) return end if route_hash['call_route'].class == Hash call_route = route_hash['call_route'] self.routing_table = call_route['routing_table'].downcase self.name = call_route['name'].downcase self.position = call_route['position'] self.endpoint_type = call_route['endpoint_type'] endpoint_from_type_name(call_route['endpoint_type'], call_route['endpoint']) if route_hash['call_route']['route_elements'] && route_hash['call_route']['route_elements']['route_element'] if route_hash['call_route']['route_elements']['route_element'].class == Hash @elements_array = [route_hash['call_route']['route_elements']['route_element']] else @elements_array = route_hash['call_route']['route_elements']['route_element'] end end elsif route_hash['route_elements'].class == Hash && route_hash['route_elements']['route_element'] if route_hash['route_elements']['route_element'].class == Hash @elements_array = [route_hash['route_elements']['route_element']] else @elements_array = route_hash['route_elements']['route_element'] end end end def self.test_route(table, caller) arguments = ["'#{table}' table"] caller.each do |key, value| arguments << "'#{value}' '#{key}'" end require 'freeswitch_event' result = FreeswitchAPI.api_result(FreeswitchAPI.api('lua', 'test_route.lua', arguments.join(' '))) if result.blank? then return end return JSON.parse(result) end private def endpoint_from_type_name(endpoint_type, endpoint_name) endpoint_type = endpoint_type.to_s.downcase if endpoint_type == 'phonenumber' self.endpoint_type = 'PhoneNumber' self.endpoint_id = nil elsif endpoint_type == 'gateway' gateway = Gateway.where(:name => endpoint_name).first if gateway self.endpoint_type ='Gateway' self.endpoint_id = gateway.id end end end def create_elements if @elements_array && @elements_array.any? @elements_array.each do |element_hash| element = self.route_elements.create(element_hash) end end end end
# frozen_string_literal: true RSpec.describe Ringu do it "has a version number" do expect(Ringu::VERSION).not_to be nil end end
class Deal < Highrise::Deal include ReadOnlyResource def self.with_preloaded_deal_data(deals) deals.tap do |deals| DealDataPreloader.new(deals).preload end end def self.filter(filter, deals) filter_method = "#{filter}_filter" send(filter_method, deals) if respond_to?(filter_method) end def deal_data=(deal_data) @deal_data = deal_data || DealData.new(:deal_id => self.id) end def deal_data @deal_data ||= find_or_build_deal_data end def update_deal_data(attributes) deal_data.update_attributes(attributes.fetch("deal_data", {})) end def daily_budget deal_data.daily_budget(price || 0) end delegate :start_date, :end_date, :date_range, :probability, :average_rate, :to => :deal_data, :allow_nil => true private def self.missing_data_filter(deals) [].tap do |deals_missing_data| deals.each do |deal| unless deal.start_date && deal.end_date && deal.price deals_missing_data.push(deal) end end end end def find_or_build_deal_data DealData.where(:deal_id => self.id).first_or_initialize end end
require 'spec_helper' require 'yt/models/playlist_item' describe Yt::PlaylistItem, :device_app do subject(:item) { Yt::PlaylistItem.new id: id, auth: $account } context 'given an existing playlist item' do let(:id) { 'UExTV1lrWXpPclBNVDlwSkc1U3Q1RzBXRGFsaFJ6R2tVNC4yQUE2Q0JEMTk4NTM3RTZC' } it 'returns valid metadata' do expect(item.title).to be_a String expect(item.description).to be_a String expect(item.thumbnail_url).to be_a String expect(item.published_at).to be_a Time expect(item.channel_id).to be_a String expect(item.channel_title).to be_a String expect(item.playlist_id).to be_a String expect(item.position).to be_an Integer expect(item.video_id).to be_a String expect(item.video).to be_a Yt::Video expect(item.privacy_status).to be_a String end end context 'given an unknown playlist item' do let(:id) { 'not-a-playlist-item-id' } it { expect{item.snippet}.to raise_error Yt::Errors::RequestError } end context 'given one of my own playlist items that I want to update' do before(:all) do @my_playlist = $account.create_playlist title: "Yt Test Update Playlist Item #{rand}" @my_playlist.add_video '9bZkp7q19f0' @my_playlist_item = @my_playlist.add_video '9bZkp7q19f0' end after(:all) { @my_playlist.delete } let(:id) { @my_playlist_item.id } let!(:old_title) { @my_playlist_item.title } let!(:old_privacy_status) { @my_playlist_item.privacy_status } let(:update) { @my_playlist_item.update attrs } context 'given I update the position' do let(:attrs) { {position: 0} } specify 'only updates the position' do expect(update).to be true expect(@my_playlist_item.position).to be 0 expect(@my_playlist_item.title).to eq old_title expect(@my_playlist_item.privacy_status).to eq old_privacy_status end end end end
class History < ApplicationRecord has_one :buy belongs_to :item belongs_to :user end
class DishesController < ApplicationController def index end def show @dish = Dish.find params[:id] end def new @restaurant = Restaurant.find params[:restaurant_id] @dish = Dish.new respond_to do |format| format.html { render 'new' } format.js { render 'new.js.erb' } end end def create @dish = Dish.new dish_params if @dish.save redirect_to restaurant_url(@dish.restaurant_id) else render 'new' end end def destroy end def edit @dish = Dish.find params[:id] @restaurant = @dish.restaurant respond_to do |format| format.html { render 'edit' } format.js { render 'edit.js.erb' } end end def update @dish = Dish.find params[:id] if @dish.update(dish_params) redirect_to restaurant_url(@dish.restaurant_id) else render 'edit' end end private def dish_params params.require(:dish).permit(:restaurant_id, :name, :price, :image_url) end end
h = {} puts h.class h = { :name=> "John", :lastname=> "Doe" } puts h # symbols are unique objects and refer to the same object. symbols are mainly used for has keys # h = {"name"=> "John"} # another way to assign hash keys and values
class Comment < ApplicationRecord belongs_to :user belongs_to :product validates :content, presence: true validates :content, :length => { :maximum => 1000, :minimum => 1 } def created_time created_at.strftime("%m/%d/%y at %l:%M %p") end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # class Object def remove_subclasses_of(*superclasses) #:nodoc: Class.remove_class(*subclasses_of(*superclasses)) end begin ObjectSpace.each_object(Class.new) {} # Exclude this class unless it's a subclass of our supers and is defined. # We check defined? in case we find a removed class that has yet to be # garbage collected. This also fails for anonymous classes -- please # submit a patch if you have a workaround. def subclasses_of(*superclasses) #:nodoc: subclasses = [] superclasses.each do |sup| ObjectSpace.each_object(class << sup; self; end) do |k| if k != sup && (k.name.blank? || eval("defined?(::#{k}) && ::#{k}.object_id == k.object_id")) subclasses << k end end end subclasses end rescue RuntimeError # JRuby and any implementations which cannot handle the objectspace traversal # above fall back to this implementation def subclasses_of(*superclasses) #:nodoc: subclasses = [] superclasses.each do |sup| ObjectSpace.each_object(Class) do |k| if superclasses.any? { |superclass| k < superclass } && (k.name.blank? || eval("defined?(::#{k}) && ::#{k}.object_id == k.object_id")) subclasses << k end end subclasses.uniq! end subclasses end end def extended_by #:nodoc: ancestors = class << self; ancestors end ancestors.select { |mod| mod.class == Module } - [ Object, Kernel ] end def extend_with_included_modules_from(object) #:nodoc: object.extended_by.each { |mod| extend mod } end unless defined? instance_exec # 1.9 module InstanceExecMethods #:nodoc: end include InstanceExecMethods # Evaluate the block with the given arguments within the context of # this object, so self is set to the method receiver. # # From Mauricio's http://eigenclass.org/hiki/bounded+space+instance_exec def instance_exec(*args, &block) begin old_critical, Thread.critical = Thread.critical, true n = 0 n += 1 while respond_to?(method_name = "__instance_exec#{n}") InstanceExecMethods.module_eval { define_method(method_name, &block) } ensure Thread.critical = old_critical end begin send(method_name, *args) ensure InstanceExecMethods.module_eval { remove_method(method_name) } rescue nil end end end end
# Build a class AnimalSorter that accepts a list of animals on # initialization. # Define a to_a method to account for the species in the test suite. # Return an array that contains two arrays, the first one # should include the sea creatures, the second, land animals. # Read the test suite for an example of a nested array. require 'pry' class AnimalSorter attr_accessor :animals def initialize(animals) @animals = animals end def to_a animal_array = [] sea_animals = [] land_animals = [] @animals.each_with_index do |animal, index| # binding.pry if index % 2 == 0 sea_animals << animal else land_animals << animal end end # binding.pry animal_array.push(sea_animals, land_animals) end end
# Configure Rails Environment ENV["RAILS_ENV"] = "test" # https://github.com/rails/rails-controller-testing # Even with the rails-controller-testing gem installed, we need these two lines to enable it require 'rails-controller-testing' Rails::Controller::Testing.install # Need to use .env to shim in the CAS server URL so that I don't have to hard-code it into the source code and expose my # private URL. This means I need to have a .env file at the root directory of the gem. I got this from # https://github.com/bkeepers/dotenv#sinatra-or-plain-ol-ruby require "dotenv" Dotenv.load require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" # Filter out Minitest backtrace while allowing backtrace from other libraries # to be shown. Minitest.backtrace_filter = Minitest::BacktraceFilter.new # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # Load fixtures from the engine if ActiveSupport::TestCase.respond_to?(:fixture_path=) ActiveSupport::TestCase.fixture_path = File.expand_path("../dummy/test/fixtures", __FILE__) end
require 'test_helper' class CrunchAlgorithmsControllerTest < ActionController::TestCase setup do @crunch_algorithm = crunch_algorithms(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:crunch_algorithms) end test "should get new" do get :new assert_response :success end test "should create crunch_algorithm" do assert_difference('CrunchAlgorithm.count') do post :create, crunch_algorithm: { functions: @crunch_algorithm.functions, name: @crunch_algorithm.name, report_id: @crunch_algorithm.report_id, type: @crunch_algorithm.type } end assert_redirected_to crunch_algorithm_path(assigns(:crunch_algorithm)) end test "should show crunch_algorithm" do get :show, id: @crunch_algorithm assert_response :success end test "should get edit" do get :edit, id: @crunch_algorithm assert_response :success end test "should update crunch_algorithm" do patch :update, id: @crunch_algorithm, crunch_algorithm: { functions: @crunch_algorithm.functions, name: @crunch_algorithm.name, report_id: @crunch_algorithm.report_id, type: @crunch_algorithm.type } assert_redirected_to crunch_algorithm_path(assigns(:crunch_algorithm)) end test "should destroy crunch_algorithm" do assert_difference('CrunchAlgorithm.count', -1) do delete :destroy, id: @crunch_algorithm end assert_redirected_to crunch_algorithms_path end end
# Represents all baskets class Baskets attr_reader :rows def initialize(file) @rows = [] parse_file(file) end private # Parses the whole file, turning it into sets of item ids def parse_file(file) File.readlines(file).each do |line| parse_line(line) end end # Parses one line, turning it into a set if item ids def parse_line(line) row_set = Set.new line.split(' ').each do |item_id| row_set.add(item_id.to_i) end rows << row_set end end
class Faculty include DataMapper::Resource property :id, Serial property :code, String property :name, String, :nullable => false has n, :lectures def full_name "#{code} #{name}" end # def full_name_with_lectures_count # "#{full_name} <span>(#{lectures.count})</span>" # end end
class MovieService class << self include ApiClientRequests def build(movie_json) body = movie_json.respond_to?(:body) ? movie_json.body : movie_json if body.is_a? Array body.map{|movie_json| Movie.new(movie_json)} else Movie.new body end end def request_uri(options={}) if options.is_a?(Fixnum) || options.is_a?(String) URI("#{ServiceHelper.uri_for('movie', protocol = 'https', host: :external)}/movies/#{options}.json") else uri = URI("#{ServiceHelper.uri_for('movie', protocol = 'https', host: :external)}/movies.json") uri.query = options.to_query uri end end end end
# encoding: UTF-8 class InvoicesController < ApplicationController before_filter :check_autentication, only: [:edit, :update, :destroy] layout 'page' # GET /invoices # GET /invoices.json before_filter :load_users, :only => [:edit, :show, :new] def index @kid_id = params[:kid_id] if current_user.try(:is_admin?) @invoices = Invoice.all(:include => :customer, :include => :seller) elsif current_user.try(:is_kid?) @invoices = Invoice.where("customer_id= ?", @kid_id) end respond_to do |format| format.html # index.html.erb format.json { render json: @invoices } end end # GET /invoices/1 # GET /invoices/1.json def show @invoice = Invoice.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @invoice } end end # GET /invoices/new # GET /invoices/new.json def new #@invoice = Invoice.new #@kid_id = params[:kid_id] #@class_invoice = ClassRegistration.where("invoice_id is ? AND kid_id= ?", nil, @kid_id) #@invoice.class_registrations = @class_invoice #@invoice.seller_id = current_user.id #@invoice.customer_id = #respond_to do |format| # format.html # new.html.erb # format.json { render json: @invoice } #end @customer_kid = Kid.includes(:user).find(params[:kid_id]) @invoice= Invoice.new(seller_id:current_user.id, customer_id:@customer_kid.user.id) @invoice.class_registrations = @invoice_class_registrations = @customer_kid.class_registrations.where(invoice_id:nil) end # GET /invoices/1/edit def edit @invoice = Invoice.find(params[:id]) end # POST /invoices # POST /invoices.json def create @invoice = Invoice.new(params[:invoice]) @invoice.seller_id = current_user.id respond_to do |format| if @invoice.save format.html { redirect_to @invoice, notice: 'فاکتور ثبت سیستم شد.' } format.json { render json: @invoice, status: :created, location: @invoice } else format.html { render action: "new" } format.json { render json: @invoice.errors, status: :unprocessable_entity } end end end # PUT /invoices/1 # PUT /invoices/1.json def update @invoice = Invoice.find(params[:id]) respond_to do |format| if @invoice.update_attributes(params[:invoice]) format.html { redirect_to @invoice, notice: 'ویرایش اطلاعات انجام شد.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @invoice.errors, status: :unprocessable_entity } end end end # DELETE /invoices/1 # DELETE /invoices/1.json def destroy @invoice = Invoice.find(params[:id]) @invoice.destroy respond_to do |format| format.html { redirect_to invoices_url } format.json { head :no_content } end end private def load_users @customers = User.customers @sellers = User.sellers end end
class AddForeignKeysToReferenceTables < ActiveRecord::Migration extend MigrationHelpers def self.up foreign_key(:accounts, :user_id, :users) foreign_key(:product_images, :product_id, :products) end def self.down # none - need the keys end end
require 'bcrypt' class User include DataMapper::Resource property :id, Serial property :name, String property :email, String property :password_digest, Text attr_reader :password attr_accessor :password_confirmation validates_confirmation_of :password def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end end
# frozen_string_literal: true require 'faker' FactoryBot.define do factory :company do name { Unique.next! { Faker::Company.name } } end factory :project do name { Unique.next! { Faker::Company.name } } company end factory :user do end factory :company_user do user company { Company.first || create(:company) } end factory :user_identity do email { Unique.next! { Faker::Internet.email } } uid { Unique.next! { Faker::Internet.slug } } provider { "developer" } user end end
require 'rails_helper' describe 'An admin' do describe 'visiting the dashboard can go to all items for admin' do before :each do @admin = create(:user, role: 1) @item = Item.create(title: 'bike lights', description: 'wonderful led', price: 10, image: 'https://www.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png', status: 1) @item2 = Item.create(title: 'wheels', description: 'circle', price: 90, image: 'https://www.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png', status: 0) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@admin) end it 'sees link to view all items and click on it current path should be "/admin/bike-shop"' do visit admin_dashboard_index_path expect(page).to have_link('All Items') click_link 'All Items' expect(current_path).to eq(admin_bike_shop_path) end it 'can see all accessories in a table on admin/bike-shop with a thumbnail of the image, description, status' do visit admin_bike_shop_path expect(page).to have_content(@item.description) expect(page).to have_content(@item.title) expect(page).to have_content(@item.price) expect(page).to have_content(@item.status) expect(page).to have_content(@item2.description) expect(page).to have_content(@item2.title) expect(page).to have_content(@item2.price) expect(page).to have_content(@item2.status) end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Mirador viewer', type: :system do context 'Configure Mirador' do it 'configures a manifest given an integer value' do value = 123_456 visit "/mirador/#{value}" expect(page.html).to match(/const manifest =.*#{value}/) end it 'contains a noindex tag' do value = 123_456 visit "/mirador/#{value}" expect(page).to have_css("meta[name=robots][content=noindex]", visible: false) end it 'builds a blank configuration given an invalid value' do value = '1_malicious_stuff_here' visit "/mirador/#{value}" expect(page.html).not_to match(/const manifest/) expect(page.html).not_to include value end end end
require 'rails_helper' RSpec.describe Application, type: :model do describe 'relationships' do it {should have_many :application_pets} it {should have_many(:pets).through(:application_pets)} end describe 'class methods' do describe '#search' do it 'returns partial matches' do # Partial Matches for Pet Names # As a visitor # When I visit an application show page # And I search for Pets by name # Then I see any pet whose name PARTIALLY matches my search # For example, if I search for "fluff", my search would match pets with names "fluffy", "fluff", and "mr. fluff" @shelter_1 = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) @pet_1 = @shelter_1.pets.create(name: 'Mr. Pirate', breed: 'tuxedo shorthair', age: 5, adoptable: true) @pet_2 = @shelter_1.pets.create(name: 'Clawdia', breed: 'shorthair', age: 3, adoptable: true) @pet_3 = @shelter_1.pets.create(name: 'Ann', breed: 'ragdoll', age: 3, adoptable: false) expect(Pet.search("Claw")).to eq([@pet_2]) end it 'returns case insensitivie matches' do # Case Insensitive Matches for Pet Names # As a visitor # When I visit an application show page # And I search for Pets by name # Then my search is case insensitive # For example, if I search for "fluff", my search would match pets with names "Fluffy", "FLUFF", and "Mr. FlUfF" @shelter_1 = Shelter.create(name: 'Aurora shelter', city: 'Aurora, CO', foster_program: false, rank: 9) @pet_1 = @shelter_1.pets.create(name: 'Mr. Pirate', breed: 'tuxedo shorthair', age: 5, adoptable: true) @pet_2 = @shelter_1.pets.create(name: 'Clawdia', breed: 'shorthair', age: 3, adoptable: true) @pet_3 = @shelter_1.pets.create(name: 'Ann', breed: 'ragdoll', age: 3, adoptable: false) expect(Pet.search("cLaW")).to eq([@pet_2]) end end describe '#pending_applications' do it 'shows shelters with pending applications by name' do # For this story, you should fully leverage ActiveRecord methods in your query. # Shelters with Pending Applications # As a visitor # When I visit the admin shelter index ('/admin/shelters') # Then I see a section for "Shelter's with Pending Applications" # And in this section I see the name of every shelter that has a pending application @shelter = Shelter.create(name: 'Happy Pets', city: 'Aurora, CO', foster_program: false, rank: 9) @shelter_2 = Shelter.create(name: 'RGV animal shelter', city: 'Harlingen, TX', foster_program: false, rank: 5) @shelter_3 = Shelter.create(name: 'Fancy pets of Colorado', city: 'Denver, CO', foster_program: true, rank: 10) @pet_1 = @shelter.pets.create!(adoptable: true, age: 7, breed: 'sphynx', name: 'Bare-y Manilow', shelter_id: @shelter.id) @pet_2 = @shelter_2.pets.create!(adoptable: true, age: 3, breed: 'domestic pig', name: 'Babe', shelter_id: @shelter_2.id) @pet_3 = @shelter.pets.create!(adoptable: true, age: 4, breed: 'chihuahua', name: 'Elle', shelter_id: @shelter.id) @application_1 = Application.create!(name:'Julius Caesar', street_address: '123 Copperfield Lane', city: 'Atlanta', state: 'GA', zip_code: '30301', description: 'I love dogs', application_status: 'Pending') @application_2 = Application.create!(name:'Miles Davis', street_address: 'Main St', city: 'Memphis', state: 'TN', zip_code: '75239', description: 'I love cats', application_status: 'In Progress') ApplicationPet.create!(pet: @pet_1, application: @application_1) ApplicationPet.create!(pet: @pet_2, application: @application_2) expect(Application.pending_applications.first.name).to eq(@shelter.name) end end end describe 'instance methods' do it 'should default application_status to in progress' do application = Application.new application.save application.application_status.should == 'In Progress' end it 'can check for incomplete form text fields' do application = Application.new(name: 'Peter', city: ' ') application.save application.form_incomplete?.should == true end it 'can count pets' do @shelter = Shelter.create(name: 'Happy Pets', city: 'Aurora, CO', foster_program: false, rank: 9) @pet_1 = @shelter.pets.create!(adoptable: true, age: 7, breed: 'sphynx', name: 'Bare-y Manilow', shelter_id: @shelter.id) @application_1 = Application.create!(name:'Julius Caesar', street_address: '123 Copperfield Lane', city: 'Atlanta', state: 'GA', zip_code: '30301', description: 'I love dogs', application_status: 'Pending') ApplicationPet.create!(pet: @pet_1, application: @application_1) ApplicationPet.create!(pet: @pet_1, application: @application_1) expect(@application_1.count_pets).to eq(2) end end end
require 'models/rover.rb' class MarsGrid attr_reader :height, :width, :rovers def initialize (input) @coordinates = input.split @rovers = [] parse_mars_grid parse_rovers end def within_bounds?(x, y) x >= 0 and x <= @height and y >= 0 and y <= @width end def move_rovers @rovers.each &:move end private def parse_mars_grid @height = @coordinates.shift.to_i @width = @coordinates.shift.to_i end def parse_rovers @coordinates.each_slice(4) do |x, y, face, steps| @rovers << Rover.new([x, y, face, steps], self) end end end
Rails.application.routes.draw do root 'welcome#home' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/auth/facebook/callback', to: 'sessions#create' post '/logout', to: 'sessions#destroy' resources :users, only: [:index, :show, :create] get '/signup', to:'users#new', as: 'new_user' get '/users/:id/recordbox', to: 'users#recordbox', as: 'user_recordbox' get '/users/:id/recordbox/rating', to: 'users#recordbox_rating', as: 'user_recordbox_rating' get '/users/:id/recordbox/desc', to: 'users#recordbox_desc', as: 'user_recordbox_desc' get '/users/:id/recordbox/asc', to: 'users#recordbox_asc', as: 'user_recordbox_asc' get '/users/:id/reviewed_records', to: 'users#reviewed_records', as: 'user_reviewed_records' resources :records do collection do get :rating_desc get :released_desc get :released_asc end resources :reviews, only: [:new, :create, :edit, :update, :destroy] end end
class Access < ActiveRecord::Base before_create :generate_uuid validates :request_token, :presence => true, :uniqueness => true validates :request_token_secret, :presence => true, :uniqueness => true validates :user_id, :presence => true, :uniqueness => true def generate_uuid self.uuid = SecureRandom.uuid end end
# Recipes Controller class RecipesController < ApplicationController # Authentication and Authorization hacks # before_action :authenticate_user! load_and_authorize_resource before_action :set_recipe, only: [:show, :edit, :update, :destroy] # GET /recipes # GET /recipes.json def index @recipes = if params[:tag] Recipe.tagged_with(params[:tag]) else Recipe.all end end def tags @tags = Recipe.tag_counts end # GET /recipes/1 # GET /recipes/1.json def show end # GET /recipes/new def new @recipe = Recipe.new @ingredients = Ingredient.all end # GET /recipes/1/edit def edit @ingredients = Ingredient.all end # POST /recipes # POST /recipes.json def create @recipe = Recipe.new(recipe_params) respond_to do |format| if @recipe.save format.html do redirect_to recipe_path(@recipe), notice: 'Receita criada com sucesso' end format.json { render :show, status: :created, location: @recipe } current_user.recipes << @recipe else format.html { render :new } format.json { render json: @recipe.errors, status: :unprocessable_entity } end end end # PATCH/PUT /recipes/1 # PATCH/PUT /recipes/1.json def update respond_to do |format| if @recipe.update(recipe_params) format.html do redirect_to @recipe, notice: 'Receita atualizada com sucesso' end format.json { render :show, status: :ok, location: @recipe } else format.html { render :edit } format.json do render json: @recipe.errors, status: :unprocessable_entity end end end end # DELETE /recipes/1 # DELETE /recipes/1.json def destroy @recipe.destroy respond_to do |format| format.html do redirect_to recipes_url, notice: 'Receita excluída com sucesso' end format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_recipe @recipe = Recipe.find(params[:id]) end # Never trust params from the scary net, only allow the white list through. def recipe_params params.require(:recipe).permit(:name, :description, :instructions, :tag_list, ingredient_ids: []) end end
#I received direction for the below soultion from https://stackoverflow.com/questions/35778202/how-can-i-sort-an-array-of-strings-based-on-a-non-standard-alphabet. This was my first exposure to the .tr method and it seems to be something that could be very versatile in future labs. def alphabetize(arr) alphatbet = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz" ascii = "@-\\" new_arr = arr.sort_by do |string| string.tr(alphatbet, ascii) end end
class Cour < ApplicationRecord validates :titre, presence: true, length: { in: 4..50 }, uniqueness: true validates :description, presence: true, length: { in: 4..1000 } has_many :lecons, dependent: :destroy validates_associated :lecons end
class ProductSerializer < ActiveModel::Serializer attributes :id, :name, :description, :brand, :price, :sold_at, :quantity, :need_to_rebuy, :is_favorite, :dont_rebuy, :category, :image # has_many :makeup_bags # has_many :shopping_lists end
Rails.application.routes.draw do mount Adminpanel::Engine => "/adminpanel" end
# frozen_string_literal: true require './lib/player.rb' describe Player do describe '#name' do it 'returns name' do player1 = Player.new('Andrew', 1) expect(player1.name).to eq "\e[33mAndrew\e[0m" end it 'returns name for 2nd player' do player2 = Player.new('Andrew', 2) expect(player2.name).to eq "\e[31mAndrew\e[0m" end end describe '#first?' do player1 = Player.new('Andrew', 1) player2 = Player.new('Beth', 2) it { expect(player1).to be_first } it { expect(player2).not_to be_first } end end
json.array!(@book_launchers) do |book_launcher| json.extract! book_launcher, :book_id, :launcher_id json.url book_launcher_url(book_launcher, format: :json) end