text
stringlengths
10
2.61M
class CreatePlaces < ActiveRecord::Migration def self.up create_table :places do |t| t.integer :request_id, :null=>false t.integer :country_id, :null=>false t.integer :exp_id, :null=>false end end def self.down drop_table :places end end
class Review < ApplicationRecord belongs_to :cheese belongs_to :user validates :title, presence: true validates :blocks, numericality: {only_integer: true, greater_than_or_equal_to: 0, less_than: 11} scope :top_cheeses, -> { where('blocks > ?', 8) } end
require 'open-uri' class Instagram attr_accessor :api_call, :photos_json def initialize(user_id, access_token) @api_call = "https://api.instagram.com/v1/users/#{user_id}/media/recent/?access_token=#{access_token}" open_url end def open_url @photos_json = JSON.load(open(@api_call))["data"] end end
class CartProduct < ApplicationRecord validates :customer_id, presence: true validates :product_id, presence: true validates :quantity, presence: true belongs_to :customer belongs_to :product end
require_relative "casouza_video_palindrome/version" module CasouzaVideoPalindrome # Returns true for a palindrome, false otherwise. def palindrome? if processed_content.empty? false else processed_content == processed_content.reverse end end private # Returns content for palindrome testing. def processed_content to_s.scan(/[a-z\d]/i).join.downcase end end class String include CasouzaVideoPalindrome end class Integer include CasouzaVideoPalindrome end
class Artist < ActiveRecord::Base has_many :songs def song_count self.song.count end end
module ApplicationHelper def bootstrap_class_for flash_type { success: "alert-success", error: "alert-danger", alert: "alert-warning", notice: "alert-info" }[flash_type] || "alert-" + flash_type.to_s end def alert_banner msg_type, message concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type.to_sym)}") do concat content_tag(:button, octicon('x'), class: "close", data: { dismiss: 'alert' }) concat message end) end def flash_messages(opts = {}) flash.each do |msg_type, message| alert_banner msg_type, message end nil end def embedded_svg(filename, options = {}) assets = Rails.application.assets file = assets.find_asset(filename).source.force_encoding("UTF-8") doc = Nokogiri::HTML::DocumentFragment.parse file svg = doc.at_css "svg" if options[:class].present? svg["class"] = options[:class] end if options[:width].present? svg["width"] = options[:width] end if options[:height].present? svg["height"] = options[:height] end raw doc end def num_campaigns Campaign.count end def amount_funded number_to_currency(Payment.sum(:amount), precision: 0) end end
class Image < ApplicationRecord belongs_to :product def as_json { id: id, image_url: image_url } end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :name, presence: true, length: { maximum: 20 } has_many :posts has_many :comments, dependent: :destroy has_many :likes, dependent: :destroy has_many :friends has_many :inverse_friends, class_name: 'Friend', foreign_key: 'pal_id' def pals friends.map { |friend| friend.pal if friend.accepted? }.compact end def pending_friends friends.map { |friend| friend.pal if friend.pending? }.compact end def friend_requests inverse_friends.map { |friend| friend.user unless friend.accepted? }.compact end def confirm_friend(user) pal = inverse_friends.find { |friend| friend.user == user } pal.accepted! end def friend?(user) pals.include?(user) end end
class Admin::AppController < ApplicationController layout "admin" # skip_before_action :check_admin before_action :admin_restricted private def admin_restricted if user_signed_in? && (current_user.role == :admin || current_user.role == :manager) return true else redirect_to root_url end end end
class SliceTemplate attr_reader :content attr_accessor :slices def initialize(filename) @content = File.read(filename) @slices = {} parse end def initialize_copy(other) @content = other.content.clone @slices = other.slices.clone end def [](slice_name) @slices[slice_name] = Slice.new(@slices[slice_name]) unless @slices[slice_name].instance_of?(Slice) @slices[slice_name] end def []=(slice_name, value) if value.instance_of?(Array) @slices[slice_name] = value.map do |item| item.instance_of?(Slice) ? item.render : item end else @slices[slice_name] = value end end def render render_string(@content) end alias_method :to_s, :render private def parse parse_string(@content) end def parse_string(s) s.gsub!(/<\!-- BEGIN ([^>]+) -->(.+)<\!-- END \1 -->/m).each do |match| slice_name, content = [$1.downcase, $2] parse_string(content) @slices[slice_name] = content "(#{slice_name})" end end def render_string(s) return if s.nil? s.gsub(/\(([\w\d _]+)\)/) do |match| slot_name = $1 slice = @slices[slot_name] slice.nil? ? match : render_string(slice.to_s) end end class Slice attr_reader :slots def initialize(content) @content = content parse end def parse @slots = Hash[@content.scan(/\(([\w\d _]+)\)/).map{|slot_name| [slot_name, "(#{slot_name})"] }] end def [](slot_name) @slots[slot_name] end def []=(slot_name, value) @slots[slot_name] = value end def set(slot_name, value) @slots[slot_name] = value self end def render @content.gsub(/\(([\w\d _]+)\)/) do |match| slot_name = $1 @slots[slot_name] end end alias_method :to_s, :render def initialize_copy(other) @slots = other.slots.clone end end end
require 'pathname' require 'cgi' require 'rdiscount' require_relative 'linker' # The Helpers are 'mixed' into your {Generator::Generator generator} and therefore can be used in # all template-views. # If you are searching for a method and don't know, where it may be implemented i suggest the # following inheritence chain as your search-strategy: # # Helper::IncludedHelpers -> Generator::YourGenerator -> Generator::Generator -> Renderer # # Somewhere at that chain you will find your desired function. module Helper # The Helper-methods in this module are globally used one and should not depend on the template # you are using. You will find many html-helpers around here, that are inspired by rails. module Helper include Linker # Creates a HTML-Tag and adds the attributes, specified with `attrs` # # @todo FIXME - not working with block, yet... # Rails incorporates a `capture` method, which captures the ERB-output of a block # maybe we can use something like that # `with_output_buffer` {http://apidock.com/rails/ActionView/Helpers/CaptureHelper/with_output_buffer} # # @example # tag :a, 'Hello', :href => 'http://foobar.com', :class => 'red_one' # #=> <a href="http://foobar.com" class="red_one">Hello</a> # # @param [Symbol, String] tagname # @param [String] content # @param [Hash<Symbol, String>] attrs # @return [String] html-tag # # @see #attributize def tag(tagname, content = "", attrs = {}) # Not working with blocks! if block_given? _erbout << "<#{tagname.to_s} #{attributize(content)}>" content = yield _erbout << "</#{tagname.to_s}>" else "<#{tagname.to_s} #{attributize(attrs)}>#{content}</#{tagname.to_s}>" end end # Shortens the given string to the specified length and adds '...' def truncate(string, length = 150) string.length <= length ? string : string[0..length] + " &hellip;" end # Creates a css-link tag for each input string. The resource will be linked relativly. # # @example # style 'foo', 'bar' # #=> <link rel='stylesheet' href='../css/foo.css'/> # #=> <link rel='stylesheet' href='../css/bar.css'/> # # @param [String] basename of the css-file (without extension) # @return [String] html-element to include the css-file def style(*args) args.map do |path| tag :link, "", :rel => 'stylesheet', :href => to_relative('css/'+path+'.css') end.join '' end # Creates a javascript-tag for each input string to import the script. The resource will be # linked relativly. # # @example # script 'foo', 'bar' # #=> <script href='../js/foo.js'/> # #=> <script href='../js/bar.js'/> # # @todo because those js-files are all relative links, they could be joined together and packed # afterwards # # @param [String] basename of the javascript-file (without extension) # @return [String] html-element to include the javascript-file def script(*args) args.map do |path| tag :script, "", :src => to_relative('js/'+path+'.js') end.join '' end # Removes intendation from the sources and generates a code-tag with all the required classes # to make the javascript-syntax-highlighter work. # # @example # code " function() {}" # #=> <code class="brush:js first-line:1">function(){}</code> # # @example # code " function() {}", :firstline => 15 # #=> <code class="brush:js first-line:15">function(){}</code> # # @param [String] source # @param [Hash] opts # @option opts [Numeric] :firstline (1) The line-numeration will start with that number # @option opts [String] :class ("block") A optional css-class which can be added # # @see http://alexgorbatchev.com/SyntaxHighlighter # # @return [String] the html-code-element def code(source, opts = {}) # defaults opts[:firstline] ||= 1 opts[:class] ||= "block" # find minimal intendation intendation = source.lines.map {|line| line.match(/(^\s+)/) && line.match(/(^\s+)/).captures.first.size || 0 }.min # @todo there has to be a better way for that tag :code, h(source.lines.map { |line| line[intendation .. line.size] }.join("")), :class => "#{opts[:class]} brush:js first-line:#{opts[:firstline]}" end # Escapes any html-elements in the given string # # @param [String] to_escape # @return [String] the escaped string def h(to_escape) CGI.escapeHTML(to_escape) end # Takes an absolute path and converts it to a relative one, comparing it to the **current # output path**. # # @param [String] path # @return [String] relative path def to_relative(path) path = Pathname.new(path) base = Pathname.new(@current_path) # for example /home/jsdoc/css/style.css # current: /home/jsdoc/output/Foo/Bar.html if not path.absolute? # resolve to Configs.output path = Pathname.new(Configs.output) + path end Logger.debug "Relative path '#{path}' from '#{base}'" path.relative_path_from(base).to_s end # To visually group the tokens you can specify an area. All tokens for one area (`:sidebar` in this # example) will be collected and can be rendered in the view-templates with the # {Helper::Helper#render_tokens render_tokens} helper-method. # # render_tokens :of => @code_object, :in => :sidebar # # While {Token::Handler.register registering a new token} you can use any symbol for `area`. But your tokens may not appear in # the rendered html-documentation, unless you explicitly call `render_tokens` for each area. # # The default-templates make use of the following areas: # # - :notification # - :body # - :sidebar # - :footnote # # If you don't want your token to be rendered at all, you can use `:none` as value for `area`. # # register :your_token, :area => :none # # @example render tokens of notification-area # render_tokens :of => code_object, :in => :notification # # @example exclude `@deprecated`-Tokens from output # render_tokens :of => code_object, :in => :body, :without => [:deprecated] # # @example use special default-template # render_tokens :of => code_object, :in => :sidebar, :template => 'sidebar' # # @param [Hash] opts # @option opts [CodeObject::Base] :of The object, which contains the tokens, to be rendered # @option opts [Symbol] :area The area to filter the tokens for # @option opts [Array<Symbol>, nil] :without Tokennames to be excluded from the output # @option opts [Symbol, String, nil] :template If you wan't to overwrite the default template # you can use this option. (Note: templates, specified at token-registration have higher # precedence, than this option) def render_tokens(opts = {}) code_object = opts[:of] or raise Exception.new("Parameter :of (CodeObject) required") area = opts[:in] or raise Exception.new("Parameter :in (Area) required") exclude = opts[:without] || [] rendered = "" tokens = code_object.tokens.reject {|token, v| exclude.include? token } token_groups = tokens.values.each do |tokens| # tokens is an array of Token::Token if not tokens.empty? and tokens.first.area == area template = tokens.first.template.to_s # overwriting default template with specified option[:template] if existant template = opts[:template].to_s if opts[:template] and template == 'default' rendered += render :partial => "tokens/#{template}", :locals => { :tokens => tokens } end end rendered end # Takes a hash as input and returns a string, which can be included in a html tag. # # @example # attributize :style => 'border: none;', :class => 'foo' #=> 'style="border: none;" class="foo"' # # @param [Hash] hash # @return [String] def attributize(hash) hash.map{|k,v| "#{k}=\"#{v}\""}.join ' ' end # @group Markdown # Converts input text to html using RDiscount. Afterwards all contained links are resolved and # replaced. # # More information about the markdown_opts can be found at the # {http://rubydoc.info/github/rtomayko/rdiscount/master/RDiscount RDiscount-rdoc-page}. # # @param [String] markdown_text plain text with markdown-markup # @param [Symbol, nil] markdown_opts # @return [String] converted html def to_html(markdown_text, *markdown_opts) replace_links RDiscount.new(markdown_text, *markdown_opts).to_html end # Can be used to generate a table of contents out of a markdown-text. # The generated toc contains links to the document-headlines. # To make this links actually work you need to process the document with the # :generate_toc flag, too. # # @example # <%= toc(my_text) %> # ... # <%= to_html my_text, :generate_toc %> # # @param [String] markdown_text # @return [String] html table of contents def toc(markdown_text) RDiscount.new(markdown_text, :generate_toc).toc_content end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe ApplicationController, type: :controller do it 'should redirect to profile path after login' do @user = FactoryBot.create :user, email: 'joao@example.org' target_uri = @controller.after_sign_in_path_for(@user) expect(target_uri).to eq(profile_path(email: @user.email)) end end
require 'spec_helper' resource "Greenplum DB: databases" do let(:owner) { users(:owner) } let(:owned_instance) { gpdb_instances(:owners) } let(:database) { gpdb_databases(:default) } let(:owner_account) { owned_instance.owner_account } let(:id) { database.to_param } let(:database_id) { database.to_param } let(:db_schema_1) { gpdb_schemas(:default) } let(:db_schema_2) { gpdb_schemas(:public) } before do log_in owner stub(GpdbSchema).refresh(owner_account, database) { [db_schema_1, db_schema_2] } end get "/databases/:id" do parameter :id, "The id of a database" example_request "Get a specific database" do status.should == 200 end end get "/databases/:database_id/schemas" do parameter :database_id, "The id of a database" pagination example_request "Get the list of schemas for a specific database" do status.should == 200 end end end
# Copyright © 2011-2013, Esko Luontola <www.orfjackal.net> # This software is released under the Apache License 2.0. # The license text is at http://www.apache.org/licenses/LICENSE-2.0 require 'bundler' require 'fileutils' describe Bundler, "given no javadocs," do before(:all) do @testdata = 'test-data' @sandbox = 'test-sandbox' FileUtils.rm_rf @sandbox bundler = Bundler.new bundler.password = ENV['GPG_PASSWORD'] if ENV['GPG_PASSWORD'] bundler.add_artifact(:pom, @testdata+'/annotations-pom.xml') bundler.add_artifact(:jar, @testdata+'/annotations.jar') bundler.add_artifact(:sources, @testdata+'/src_annotations.zip') bundler.create(@sandbox) end it "renames POM" do File.file?(@sandbox+"/annotations-9.0.4.pom").should == true end it "renames JAR" do File.file?(@sandbox+"/annotations-9.0.4.jar").should == true end it "renames sources JAR" do File.file?(@sandbox+"/annotations-9.0.4-sources.jar").should == true end it "creates javadoc JAR" do File.file?(@sandbox+"/annotations-9.0.4-javadoc.jar").should == true end it "signs all artifacts" do File.file?(@sandbox+"/annotations-9.0.4.pom.asc").should == true File.file?(@sandbox+"/annotations-9.0.4.jar.asc").should == true File.file?(@sandbox+"/annotations-9.0.4-sources.jar.asc").should == true File.file?(@sandbox+"/annotations-9.0.4-javadoc.jar.asc").should == true end it "bundles the generated artifacts together" do File.file?(@sandbox+"/annotations-9.0.4-bundle.jar").should == true end end
class AddAvatarToBanners < ActiveRecord::Migration def change add_column :banners, :avatar, :string end end
require 'spec_helper' describe Status do it_behaves_like 'an api model' describe 'attributes' do it { should respond_to :overall } it { should respond_to :services } end describe '#initialize' do let(:attrs) { { overall: 'running', services: [] } } subject { described_class.new(attrs) } it 'initializes the object with the passed-in attrs' do expect(subject.overall).to eq attrs[:overall] expect(subject.services).to eq attrs[:services] end end end
require 'spec_helper' describe Reservation do subject(:reservation) { Reservation.new(vmt_userid, vmt_password, vmt_url) } let(:vmt_userid) { VMT_USERID } let(:vmt_password) { VMT_PASSWORD} let(:vmt_url) { VMT_BASE_URL } describe "Should be a valid VMT Object" do it_behaves_like 'a VMT API object' end describe "#get_reservation" do let(:entity_root) {'TopologyElements'} let(:entity_node) {'TopologyElement'} let(:entity_attr) {'creationClassName'} let(:valid_data) {'Reservation'} let(:data_result) {reservation.get_reservation(reservation_ID)} let(:reservation_ID) { nil } context "will return a list of reservations" do it_behaves_like 'return entity' end context "will return a list of reservations with a specific state" do let(:data_result) {reservation.get_reservation(reservation_ID, state)} let(:state) {{:state => 'RESERVED'}} it_behaves_like 'return entity' end end describe "#get_reservation_details" do let(:reservation_ID) {'_0ZyMkOhGEeS2kPR885AurA'} let(:data_result) {reservation.get_reservation(reservation_ID)} it_behaves_like 'return entity' end end
require 'rake' namespace :wow do namespace :realm do desc "Update stored realm information from API data" task :import => :environment do |t| WowClient.new.update_realm_status end end end
class WordsTest class << self # the main function called by the CLI def process(in_file) seq_hash = proc_file(in_file) # open files sf = File.new("sequences", "w") wf = File.new("words", "w") seq_hash.keys.sort.each do |seq| sf.write(seq + "\n") wf.write(seq_hash[seq] + "\n") end # close files wf.close sf.close return true end # extract all unique 4-char letter sequences def extract_unique_sequences(word) # skip words with less than 4 chars return [] if word.length <= 3 valid_sequences = [] for i in 0..(word.length-4) lower = i upper = i + 3 my_slice = word.slice(lower..upper) # check for letters only if my_slice.match(/^[a-zA-Z]+$/) valid_sequences.push(my_slice) end end return valid_sequences.uniq end # just open a file and call proc_dict def proc_file(in_file) list = File.read(in_file).split("\n") return proc_dict(list) end # this is the workhorse of the class def proc_dict(list) seq_hash = Hash.new { |h,k| h[k] = [] } # for each word, extract the unique 4-char letter sequences list.each do |word| extract_unique_sequences(word).each do |seq| # add each word to a hash keyed by sequence seq_hash[seq].push(word) end end # filter sequences used in multiple words seq_hash.keep_if { |k, v| v.count == 1 } # move words out of single-element arrays seq_hash.dup.each do |k, v| seq_hash[k] = v[0] end # should return a hash with sequences as keys, and words as values return seq_hash end end end
require 'rails_helper' RSpec.describe 'registrar/contacts/form/_legal_document' do let(:contact) { instance_spy(Depp::Contact) } before :example do without_partial_double_verification do allow(view).to receive(:f).and_return(DefaultFormBuilder.new(:depp_contact, contact, view, {})) end assign(:contact, contact) end it 'has legal document' do render expect(rendered).to have_css('[name="depp_contact[legal_document]"]') end end
$:.push File.expand_path("../lib", __FILE__) require "guide/version" Gem::Specification.new do |s| s.name = "guide" s.version = Guide::VERSION s.authors = ["Luke Arndt", "Jordan Lewis", "Jiexin Huang"] s.email = ["luke@arndt.io", "jordan@lewis.io", "hjx500@gmail.com"] s.homepage = "https://github.com/envato/guide" s.summary = "Living documentation for your Rails application" s.description = "Document your Rails application with a living component library and styleguide" s.license = "MIT" s.metadata["homepage_uri"] = s.homepage s.metadata["source_code_uri"] = "#{s.homepage}/tree/v#{s.version}" s.metadata["changelog_uri"] = "#{s.homepage}/blob/HEAD/CHANGELOG.md" s.metadata["bug_tracker_uri"] = "#{s.homepage}/issues" s.metadata["wiki_uri"] = "#{s.homepage}/wiki" s.metadata["documentation_uri"] = "https://www.rubydoc.info/gems/#{s.name}/#{s.version}" s.files = Dir["{app,config,db,lib}/**/*", "LICENSE", "Rakefile", "README.md"] s.required_ruby_version = ">= 2.6" s.add_dependency "railties", ">= 5.2" s.add_dependency "actionpack", ">= 5.2" s.add_dependency "actionview", ">= 5.2" s.add_dependency "activemodel", ">= 5.2" s.add_dependency "sprockets-rails" s.add_development_dependency "appraisal" s.add_development_dependency "rspec-rails" s.add_development_dependency "pry" s.add_development_dependency "rails-controller-testing" end
class Room < ActiveRecord::Base belongs_to :zone delegate :world, to: :zone validate :room_fits_in_zone def try_exit(dir) case dir when 'north' r1 = zone.room(zz, yy + 1, xx) when 'south' r1 = zone.room(zz, yy - 1, xx) end if r1 return r1, nil else return self, "No such room" end end private def room_fits_in_zone if xx < 0 || xx >= zone.size errors.add(:xx, "Out of zone.size range") end if yy < 0 || yy >= zone.size errors.add(:yy, "Out of zone.size range") end if zz < 0 || zz >= zone.size errors.add(:zz, "Out of zone.size range") end end end
## # This class defines the abilities and privileges belonging to the various # user roles. class Ability include CanCan::Ability def initialize(user) alias_action :manage, :change_state, to: :everything user ||= User.new roles = user.roles.map(&:value) grant_generic_privileges(roles) grant_editor_privileges(roles) grant_pdf_privileges(roles) grant_publishing_privileges(roles) grant_edit_user_role_privileges(roles) grant_admin_privileges(roles) end def grant_generic_privileges(roles) return if (roles & [ UserRole::ADMIN, UserRole::PUBLISHER, UserRole::EDITOR_IN_CHIEF, UserRole::PRODUCTION, UserRole::NEWS_EDITOR, UserRole::OPINION_EDITOR, UserRole::CAMPUS_LIFE_EDITOR, UserRole::ARTS_EDITOR, UserRole::SPORTS_EDITOR, UserRole::PHOTO_EDITOR, UserRole::ONLINE_MEDIA_EDITOR, UserRole::STAFF, UserRole::BUSINESS ]).empty? can [:index, :show, :edit, :new, :create, :update, :assets_list, :as_xml], Article can [:index, :show, :revert], ArticleVersion can [:index, :show, :edit, :new, :create, :update], Author can [:index, :show, :edit, :new, :create, :update, :direct, :assign_piece, :unassign_piece], Image can [:index, :lookup], Issue can [:index], Section can [:index, :show], User end def grant_editor_privileges(roles) return if (roles & [ UserRole::ADMIN, UserRole::PUBLISHER, UserRole::EDITOR_IN_CHIEF, UserRole::PRODUCTION, UserRole::NEWS_EDITOR, UserRole::OPINION_EDITOR, UserRole::CAMPUS_LIFE_EDITOR, UserRole::ARTS_EDITOR, UserRole::SPORTS_EDITOR, UserRole::PHOTO_EDITOR, UserRole::ONLINE_MEDIA_EDITOR ]).empty? can :create, Issue can :update_rank, Article can :update_web_status, ArticleVersion end def grant_pdf_privileges(roles) return if (roles & [ UserRole::ADMIN, UserRole::PUBLISHER, UserRole::EDITOR_IN_CHIEF, UserRole::PRODUCTION ]).empty? can [:upload_pdf_form, :upload_pdf, :remove_pdf], Issue end def grant_publishing_privileges(roles) return if (roles & [ UserRole::ADMIN, UserRole::PUBLISHER, UserRole::EDITOR_IN_CHIEF ]).empty? can [:publish, :mark_print_ready], ArticleVersion end def grant_edit_user_role_privileges(roles) return if (roles & [ UserRole::ADMIN, UserRole::EDITOR_IN_CHIEF ]).empty? can [:edit, :update], User do |u| not(u.roles.map(&:value).include? UserRole::ADMIN) end end def grant_admin_privileges(roles) return unless roles.include? UserRole::ADMIN can :everything, :all end end
# @param {Array<Integer>} nums # @param {Integer} n # @return {Array<Integer>} def shuffle(nums, n) shuffled = [] for i in 0..n-1 do pX = i pY = (n)+i shuffled.push(nums[pX]) shuffled.push(nums[pY]) end shuffled end puts shuffle([2,5,1,3,4,7],3)
activity Java::org.ruboto.test_app.OptionMenuActivity setup do |activity| start = Time.now loop do @text_view = activity.findViewById(42) break if @text_view || (Time.now - start > 60) sleep 1 end assert @text_view end test('option_menu changes text') do |activity| assert_equal "What hath Matz wrought?", @text_view.text activity.window.performPanelIdentifierAction(android.view.Window::FEATURE_OPTIONS_PANEL, 0, 0) # FIXME(rscottm): Does not work in Ruby 1.9 mode assert_equal("What hath Matz wrought!", @text_view.text) if RUBY_VERSION < '1.9' end
class TagSerializer < ActiveModel::Serializer attributes :id, :title belongs_to :task end
class StartupsBadges < ActiveRecord::Base has_and_belongs_to_many :badges has_and_belongs_to_many :startups # Definition: This method takes the startup_id and calls different helper methods to set achieved badges. # It then returns an array of recently achieved badges' description. # Input: startup_id. # Output: recently_achieved_badge. # Author: Yomn El-Mistikawy. def self.set_badges(entity_id) startup = Startup.find_by_entity_id(entity_id) recently_achieved_badge = [] recently_achieved_badge = recently_achieved_badge + StartupsBadges.set_year_badges(startup.id) recently_achieved_badge = recently_achieved_badge + StartupsBadges.set_view_badges(entity_id) recently_achieved_badge = recently_achieved_badge + StartupsBadges.set_requirements_badges(startup.id) recently_achieved_badge = recently_achieved_badge + StartupsBadges.set_targets_badges(startup.id) recently_achieved_badge = recently_achieved_badge + StartupsBadges.set_launch_badges(startup.id) recently_achieved_badge = recently_achieved_badge + StartupsBadges.set_subscription_badges(startup.id) recently_achieved_badge = recently_achieved_badge + StartupsBadges.set_badge_collection_badges(startup.id) return recently_achieved_badge end # Definition: This method takes the startup_id and gets the unachieved badges. If the startup is # 1 years old and the badge hasn't been achieved, then the badge is added to achieved. The same condition # is done for 2.5 years and 5 years and also the lower level badges are set as bypassed. It then returns # an array of recently achieved year badges' description. # Input: startup_id. # Output: recently_achieved_badge. # Author: Yomn El-Mistikawy. def self.set_year_badges(startup_id) startup = Startup.find(startup_id) unachieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup_id, 0, 0, 0, 0) recently_achieved_badge = [] if (startup.number_of_working_years >= 1 && (unachieved_badges.where(:id => 1)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 1, :bypassed => 0) recently_achieved_badge = recently_achieved_badge + [Badge.find(1)] end if (startup.number_of_working_years >= 2.5 && (unachieved_badges.where(:id => 2)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 2, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 1).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(2)] end if (startup.number_of_working_years >= 5 && (unachieved_badges.where(:id => 3)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 3, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 2).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(3)] end return recently_achieved_badge end # Definition: This method takes the startup_id and gets the unachieved badges. It then counts get the number of views # the startup's profile and gives badges when the number of views reaches 1000, 5000 or 10000. It also sets the lower level badges to bypassed. # Input: startup_id. # Output: recently_achieved_badge. # Author: Yomn El-Mistikawy. def self.set_view_badges(entity_id) entity = Entity.find(entity_id) number_of_views = entity.impressionist_count(:filter=>:session_hash) startup = Startup.find_by_entity_id(entity_id) unachieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup.id, 0, 0, 0, 0) recently_achieved_badge = [] if (number_of_views >= 1000 && (unachieved_badges.where(:id => 4)).size == 1) StartupsBadges.create(:startup_id => startup.id, :badge_id => 4, :bypassed => 0) recently_achieved_badge = recently_achieved_badge + [Badge.find(4)] end if (number_of_views >= 5000 && (unachieved_badges.where(:id => 5)).size == 1) StartupsBadges.create(:startup_id => startup.id, :badge_id => 5, :bypassed => 0) StartupsBadges.where(:startup_id => startup.id, :badge_id => 4).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(5)] end if (number_of_views >= 10000 && (unachieved_badges.where(:id => 6)).size == 1) StartupsBadges.create(:startup_id => startup.id, :badge_id => 6, :bypassed => 0) StartupsBadges.where(:startup_id => startup.id, :badge_id => 5).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(6)] end return recently_achieved_badge end # Definition: This method takes the startup_id and gets the unachieved badges. It then counts the number # of requirements met in all of the startups projects and gives badges when the number of requirements met reaches # 50, 100 or 1000. It also sets the lower level badges to bypassed. # Input: startup_id. # Output: recently_achieved_badge. # Author: Yomn El-Mistikawy. def self.set_requirements_badges(startup_id) unachieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup_id, 0, 0, 0, 0) requirements_met = ProjectRequirement.where(:project_id => ProjectsStartup.select(:project_id).where(:startup_id => startup_id), :reached => 1) recently_achieved_badge = [] if (requirements_met.count >= 50 && (unachieved_badges.where(:id => 7)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 7, :bypassed => 0) recently_achieved_badge = recently_achieved_badge + [Badge.find(7)] end if (requirements_met.count >= 100 && (unachieved_badges.where(:id => 8)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 8, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 7).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(8)] end if (requirements_met.count >= 1000 && (unachieved_badges.where(:id => 9)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 9, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 8).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(9)] end return recently_achieved_badge end # Definition: This method takes the startup_id and gets the unachieved badges. It then counts the number # of targets met in all of the startups projects and gives badges when the number of targets met reaches # 50, 100 or 1000. It also sets the lower level badges to bypassed. # Input: startup_id. # Output: recently_achieved_badge. # Author: Yomn El-Mistikawy. def self.set_targets_badges(startup_id) unachieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup_id, 0, 0, 0, 0) targets_met = ProjectTarget.where(:project_id => ProjectsStartup.select(:project_id).where(:startup_id => startup_id), :reached => 1) recently_achieved_badge = [] if (targets_met.count >= 50 && (unachieved_badges.where(:id => 10)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 10, :bypassed => 0) recently_achieved_badge = recently_achieved_badge + [Badge.find(10)] end if (targets_met.count >= 100 && (unachieved_badges.where(:id => 11)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 11, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 10).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(11)] end if (targets_met.count >= 1000 && (unachieved_badges.where(:id => 12)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 12, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 11).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(12)] end return recently_achieved_badge end # Definition: This method takes the startup_id and gets the unachieved badges. It then counts the number # of projects that have been launched by the startup and gives badges when the startup launches 5, 10 or 50 # projects. It also sets the lower level badges to bypassed. # Input: startup_id. # Output: recently_achieved_badge. # Author: Yomn El-Mistikawy. def self.set_launch_badges(startup_id) launched_projects = Project.where(:id => ProjectsStartup.select(:project_id).where(:startup_id => startup_id), :launch => 1) unachieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup_id, 0, 0, 0, 0) recently_achieved_badge = [] if (launched_projects.count >= 5 && (unachieved_badges.where(:id => 13)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 13, :bypassed => 0) recently_achieved_badge = recently_achieved_badge + [Badge.find(13)] end if (launched_projects.count >= 10 && (unachieved_badges.where(:id => 14)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 14, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 13).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(14)] end if (launched_projects.count >= 50 && (unachieved_badges.where(:id => 15)).size == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 15, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 14).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(15)] end return recently_achieved_badge end # Definition: This method takes the startup_id and gets the unachieved badges. A badge is given when the # startup gets 100, 500 and 5000 subscriptions. When a new badge is given lower level badges are set as # bypassed. It then returns an array of recently achieved year badges' description. # Input: startup_id. # Output: recently_achieved_badge. # Author: Yomn El-Mistikawy. def self.set_subscription_badges(startup_id) unachieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup_id, 0, 0, 0, 0) entity_id = Startup.select(:entity_id).where(:id => startup_id) number_of_subscribers = Subscription.where(:subscribee_id => entity_id).count recently_achieved_badge = [] if (number_of_subscribers >= 100 && (unachieved_badges.where(:id => 16)).count == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 16, :bypassed => 0) recently_achieved_badge = recently_achieved_badge + [Badge.find(16)] end if (number_of_subscribers >= 500 && (unachieved_badges.where(:id => 17)).count == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 17, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 16).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(17)] end if (number_of_subscribers >= 5000 && (unachieved_badges.where(:id => 18)).count == 1) StartupsBadges.create(:startup_id => startup_id, :badge_id => 18, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 17).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(18)] end return recently_achieved_badge end # Definition: This method takes the startup_id and gets the unachieved badges. If the startup has # achieved all of the badges in a certain category, then a platinum badge is given and the lower level badges # are set as bypassed. Moreover, if all badges are collected, a platinum badge is given and lower level badges # are bypassed. # Input: startup_id. # Output: recently_achieved_badge. # Author: Yomn El-Mistikawy. def self.set_badge_collection_badges(startup_id) unachieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup_id, 0, 0, 0, 0) achieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup_id, 1, 1, 0, 0) recently_achieved_badge = [] if (unachieved_badges.where(:id => 19).size == 1) if (achieved_badges.where(:category => "year").size == 3) StartupsBadges.create(:startup_id => startup_id, :badge_id => 19, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 3).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(19)] end end if (unachieved_badges.where(:id => 20).size == 1) if (achieved_badges.where(:category => "view").size == 3) StartupsBadges.create(:startup_id => startup_id, :badge_id => 20, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 6).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(20)] end end if (unachieved_badges.where(:id => 21).size == 1) if (achieved_badges.where(:category => "requirements").size == 3) StartupsBadges.create(:startup_id => startup_id, :badge_id => 21,:bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 9).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(21)] end end if (unachieved_badges.where(:id => 22).size == 1) if (achieved_badges.where(:category => "targets").size == 3) StartupsBadges.create(:startup_id => startup_id, :badge_id => 22, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 12).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(22)] end end if (unachieved_badges.where(:id => 23).size == 1) if (achieved_badges.where(:category => "launched").size == 3) StartupsBadges.create(:startup_id => startup_id, :badge_id => 23, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 15).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(23)] end end if (unachieved_badges.where(:id => 24).size == 1) if (achieved_badges.where(:category => "subscribe").size == 3) StartupsBadges.create(:startup_id => startup_id, :badge_id => 24, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => 18).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(24)] end end if (unachieved_badges.where(:id => 25).size == 1) achieved_badges = StartupsBadges.get_achieved_unachieved_badges(startup_id, 1, 1, 0, 0) if (achieved_badges.where(:category => "collector").size == 6) StartupsBadges.create(:startup_id => startup_id, :badge_id => 25, :bypassed => 0) StartupsBadges.where(:startup_id => startup_id, :badge_id => [19,20,21,22,23,24]).update_all(:bypassed => 1) recently_achieved_badge = recently_achieved_badge + [Badge.find(25)] end end return recently_achieved_badge end # Definition: This method takes the achieved and bypassed boolean values and startup_id. # If the achieved and bypassed are equal to 1 then it returns all achieved badges. If the achieved is equal to 0, # then the unachieved badges are returned. If the achieved value is 1 and the bypassed is 0 then it returns only the # not bypassed badges. # Input: startup_id, achieved_or_not, bypassed. # Output: unachieved/achieved/bypassed/not bypassed badges. # Author: Yomn El-Mistikawy. def self.get_achieved_unachieved_badges(startup_id, achieved, bypassed, entity, category) if(entity == 1) startup_id = Startup.select(:id).where(:entity_id => startup_id) end achieved_badges_id = StartupsBadges.select(:badge_id).where(:startup_id => startup_id) if (achieved == 1 && bypassed == 1) return Badge.where(:id => achieved_badges_id).order(id: :asc) else if (achieved == 0 && category != 0) return Badge.where(:category => category).where.not(:id => achieved_badges_id).order(id: :asc) else if (achieved == 0) return Badge.where.not(:id => achieved_badges_id).order(id: :asc) else if (achieved == 1 && bypassed == 0) achieved_badges_id = StartupsBadges.select(:badge_id).where(:startup_id => startup_id, :bypassed => 0) return Badge.where(:id => achieved_badges_id).order(id: :asc) end end end end end end
class AddTypeToComboItem < ActiveRecord::Migration def change add_column :combo_items, :combo_type, :string end end
require "spec_helper" describe ObservationTutorialsController do describe "routing" do it "routes to #index" do get("/observation_tutorials").should route_to("observation_tutorials#index") end it "routes to #new" do get("/observation_tutorials/new").should route_to("observation_tutorials#new") end it "routes to #show" do get("/observation_tutorials/1").should route_to("observation_tutorials#show", :id => "1") end it "routes to #edit" do get("/observation_tutorials/1/edit").should route_to("observation_tutorials#edit", :id => "1") end it "routes to #create" do post("/observation_tutorials").should route_to("observation_tutorials#create") end it "routes to #update" do put("/observation_tutorials/1").should route_to("observation_tutorials#update", :id => "1") end it "routes to #destroy" do delete("/observation_tutorials/1").should route_to("observation_tutorials#destroy", :id => "1") end end end
FactoryBot.define do factory :comments do user article text { Faker::Food.description } end end
require 'byebug' class HomeController < ApplicationController before_action :set_script_obj def index @scripts = @script_obj.all end def search_by_isbn @script = @script_obj.by_isbn(params[:isbn]) if @script render :show else flash[:notice] = 'No matching!' redirect_to root_path end end def search_by_authors_email @scripts = @script_obj.by_authors_email(params[:authors_email]) if @scripts.any? render :scripts else flash[:notice] = 'No matching!' redirect_to root_path end end def sort @scripts = @script_obj.all_sorted_by_title render :scripts end private def set_script_obj @script_obj = Script.new end end
# frozen_string_literal: true module Riskified module Entities ## Reference: https://apiref.riskified.com/curl/#models-payment-details PaypalDetails = Riskified::Entities::KeywordStruct.new( ##### Required ##### :payer_email, :payer_status, :payer_address_status, :protection_eligibility, #### Optional ##### :payment_status, :pending_reason, :authorization_id, :authorization_error, # [AuthorizationError] ) end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) User.destroy_all Publication.destroy_all Topic.destroy_all topic1 = Topic.create({name: 'Medicine'}) topic2 = Topic.create({name: 'Civil Engineering'}) topic3 = Topic.create({name: 'Linguistics'}) topic4 = Topic.create({name: 'Biology'}) topic5 = Topic.create({name: 'Computer Science'}) topic6 = Topic.create({name: 'Chemistry'}) topic7 = Topic.create({name: 'Environmental Engieering'}) topic8 = Topic.create({name: 'Materials Science'}) topic9 = Topic.create({name: 'Math'}) topic10 = Topic.create({name: 'Psychology'}) user = User.create({ user_name: "Mari", password: "hello", password_confirmation: "hello" }) user.publications.create({ title: 'gnomes', publication_date: '21-05-1998', synopsis: 'places to place your gnomes', topic: topic1 }) user2 = User.create({ user_name: "Cat", password: "meow", password_confirmation: "meow" }) user2.publications.create({ title: 'cats gone wild', publication_date: '10-02-1991', synopsis: 'research on wild cats', topic: topic2 })
class Page < ActiveRecord::Base include ActionView::Helpers::TextHelper has_many :navigators, as: :navigatable, dependent: :destroy validates :name, length: { maximum: 250 } validates :permalink, uniqueness: true, length: { maximum: 99 } validates :title, length: { maximum: 250 } validates :meta_description, length: { maximum: 250, allow_blank: true } before_validation :prettify_permalink attr_accessor :preview scope :published_only, -> { where(published: true) } private def prettify_permalink self.permalink = truncate(permalink.lm_strip, length: 100, separator: "-", omission: "") end end
# Probably won't work as written, and is not currently needed, but useful for reference namespace :db do desc "Erase and fill database" task :populate => :environment do require 'populator' require 'faker' [Attempt, Question, Tag, User].each(&:delete_all) # Create users 50.times do |i| created_at = Populator.value_in_range(1.year.ago..Time.now) User.create( :provider => 'facebook', :uid => rand(100000).to_s, :name => Faker::Name.name, :oauth_token => Populator.words(1), :oauth_expires_at => 14.days.from_now, :created_at => created_at, :updated_at => created_at ) end # Create tags 10.times do |i| created_at = Populator.value_in_range(1.year.ago..Time.now) Tag.create( :name => Populator.words(1), :created_at => created_at, :updated_at => created_at ) end # Create questions @users = User.all 25.times do |i| user = @users.sample created_at = Populator.value_in_range(user.created_at..Time.now.to_datetime) user.questions.create( :xml => Populator.words(1..5), :created_at => created_at, :updated_at => created_at ) end # Create attempts @questions = Question.all 50.times do |i| user = @users.sample question = @questions.sample earliest_time = [user.created_at, question.created_at].max created_at = Populator.value_in_range(earliest_time..Time.now.to_datetime) Attempt.create( :user_id => user.id, :question_id => question.id, :answer => Populator.words(1..3), :created_at => created_at, :is_correct => [true, false].sample, :cohort_id => rand(100) ) end # Create questions_tags entries @tags = Tag.all 50.times do |i| question = @questions.sample tag = @tags.sample question.tags << tag end end end
class RenameTargetHealthAttributeRatingsToHealthAssessments < ActiveRecord::Migration[5.2] def change rename_table :target_health_attribute_ratings, :health_attributes end end
# == Schema Information # # Table name: products # # id :integer(4) not null, primary key # name :string(255) # serial_number :string(255) # date_ordered :date # date_received :date # date_invoiced :date # vendor_invoice :string(255) # scc_invoice :string(255) # quantity :integer(10) # dollar_amount :integer(10) # warranty_years :integer(4) # warranty_days :integer(4) # item :integer(4) # comments :text # created_at :datetime not null # updated_at :datetime not null # vendor_id :integer(4) # customer_id :integer(4) # category_id :integer(4) # department :string(255) # class Product < ActiveRecord::Base attr_protected :id belongs_to :customer belongs_to :vendor belongs_to :category validates :name, :customer, :vendor, :presence => true def self.search(search) if search where('name LIKE ?', "%#{search}%") else scoped end end end
#### # # Product # # Product is a line item on the invoice. # # Invoices are created of property related information and the billed charges # for a period. The product are these billed charges plus any arrears. # #### # class Product < ApplicationRecord include Comparable enum payment_type: { manual: 0, automatic: 1 } belongs_to :invoice, inverse_of: :products validates :amount, :charge_type, :date_due, presence: true validates :payment_type, inclusion: { in: payment_types.keys } def period (period_first..period_last) end def period=(bill_range) self.period_first = bill_range.first self.period_last = bill_range.last end def arrears? charge_type == ChargeTypes::ARREARS end # Wrapper for the arguments required for an Arrears product item. # All the other product items are taken from the debit. # def self.arrears(account:, date_due:) Product.new charge_type: ChargeTypes::ARREARS, date_due: date_due, payment_type: 'automatic', amount: account.balance_all_credits(to_time: date_due), balance: account.balance_all_credits(to_time: date_due) end # Scope to return products that trigger the back page of the invoice # These are displayed on the backpage. # def self.page2 where(charge_type: [ChargeTypes::GROUND_RENT, ChargeTypes::GARAGE_GROUND_RENT]) .order(charge_type: :desc).first end # ordering line item charges on the first page of the invoice. # def self.order_by_date_then_charge order(date_due: :asc, charge_type: :asc) end # Does the product require additional explanation typically # on the back page of the invoice. # def page2? charge_type.in? [ChargeTypes::GROUND_RENT, ChargeTypes::GARAGE_GROUND_RENT] end def <=> other return nil unless other.is_a?(self.class) [date_due, charge_type, amount, period_first, period_last] <=> [other.date_due, other.charge_type, other.amount, other.period_first, other.period_last] end def to_s "charge_type: #{charge_type} date_due: #{date_due} " \ "amount: #{amount.round(2)} " \ "period: #{period_first}..#{period_last}, " \ "balance: #{balance ? balance.round(2) : ''}" end end
require 'optparse' require_relative 'speech' require_relative 'version' module Txt2Speech class Application def initialize options = {} OptionParser.new do |opts| opts.banner = "Usage: txt2speech [options]" opts.on("-o", "--output [String]", String, "Output file") {|o| options[:out] = o } opts.on("-r", "--read [String]", String, "Read text") {|o| options[:read] = o} opts.on("-f", "--file", "From file") {|o| options[:file] = o } opts.on("-l", "--lang [String]", String, "Language of text") {|o| options[:lang] = o } opts.on("-v", "--version", "Show version") {|o| options[:version] = Txt2Speech::VERSION } end.parse! if options[:version] puts options[:version] else out = options[:out].to_s.length > 0 ? options[:out] : "out.mpg" attrs = [options[:read], options[:lang] || "en"] attrs.unshift(options[:file] ? :load : :new) f = Txt2Speech::Speech.send(*attrs) f.save(out) end end end end
# vim: set expandtab ts=2 sw=2 nowrap ft=ruby ff=unix : */ require './lib/api-server/users-handler' module ApiServer class UsersPostHandler < UsersHandler # Insert a new record. def execute_insert_query(filtered_params) table = Arel::Table.new(:users) manager = Arel::InsertManager.new(Arel::Table.engine) manager.into(table) manager.values = Arel::Nodes::Values.new([filtered_params[:name]]) manager.columns << table[:name] query_execute(manager) end def insert_user(filtered_params) result = execute_insert_query(filtered_params) respond_users({ :id => connection.last_inserted_id(result), :fields => '*', }) end def handler_post_users filtered_params = { :name => params[:name].intern, # meta parameters :format => params[:format].intern || :json, } if filtered_params[:name] insert_user(filtered_params) else 'name is required' end end # Insert a new record. post '/v1/users.?:format?' do handler_post_users end end end
require 'yaml/store' require 'pry' class RobotWorld attr_reader :database def initialize(database) @database = database end def create(robot) if robot.values.all? {|value| value.empty?} robot = fake_robot raw_robots.insert(robot) else raw_robots.insert(robot) end end def fake_robot name = Faker::Name.name city = Faker::Address.city state = Faker::Address.state birthdate = Faker::Date.birthday.strftime("%F") date_hired = Faker::Date.between(birthdate, Date.today) department = Faker::Commerce.department(1) photo = Faker::Avatar.image {"name"=>name, "city"=>city, "state"=>state, "birthdate"=>birthdate, "date_hired"=>date_hired, "department"=>department, "photo"=>photo} end def raw_robots database.from(:robots) end def all raw_robots.map {|robot| Robot.new(robot)} end def find(id) all.find {|robot| robot.id == id} end def update(id, robot) raw_robots.where(:id => id).update(robot) end def delete(id) raw_robots.where(:id => id).delete end def find_by_name(name) potential_robot_matches = all.find_all do |robot| name.downcase.chars.all? do |letter| robot.name.downcase.include?(letter) end end filter_matches(potential_robot_matches, name) end def filter_matches(potential_matches, name) potential_matches.find_all do |robot| robot.name.downcase.chars.all? do |letter| name.downcase.count(letter) <= robot.name.downcase.count(letter) end end end def delete_all raw_robots.delete end def birthyears raw_robots.map do |robot_hash| robot_hash[:birthdate].split("-")[0].to_i end end def average_age avg_birthyear = birthyears.reduce(:+)/birthyears.count.to_f (Date.today.strftime("%Y").to_i - avg_birthyear).round(2) end def hired_by_year hiring_dates = all.map do |robot| robot.date_hired.split("-").first.to_i end calc_robot_data(hiring_dates) end def robots_per_dept department_data = all.map {|robot|robot.department} calc_robot_data(department_data) end def robots_per_city city_data = all.map {|robot| robot.city} calc_robot_data(city_data) end def robots_per_state state_data = all.map {|robot| robot.state} calc_robot_data(state_data) end def calc_robot_data(dataset) dataset.reduce(Hash.new(0)) do |acc, data| acc[data] += 1 acc end end end
require './lab6ex.rb' class Leaberboard attr_accessor :teams_points, :score_input, :game_tracker def initialize @game_tracker = Tracker.new @teams_points = {} @score_input = {} start end def start puts "Would you like to input scores (1) or see league ranking (2)?" choice end def choice response = gets.chomp case response when "1" input_scores when "2" rankings start when "exit" puts "Bye!" else puts "What would you like to do?" choice end end def input_scores puts "Input the scores." input = gets.chomp.split.each_slice(2).to_h self.score_input = input.each_with_object({}) {|(k,v),h| h[k] = v.to_i} game_tracker.teams_used(score_input,teams_points) game_tracker.game_comparison(score_input) game_tracker.winner(teams_points,score_input) start end def rankings puts "_ _ _ _ _ MLB RANKINGS _ _ _ _ _" sorted_rankings = teams_points.sort {|a,b| a.last == b.last ? a.first <=> b.first : b.last <=> a.last} sorted_rankings.each {|k,v| puts "#{k.capitalize} : #{v}"} end end Leaberboard.new
class Api::V1::SessionsController < DeviseTokenAuth::SessionsController include NoCaching before_action :configure_permitted_parameters private def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_in, keys: [:format]) end end
class OrdersController < ApplicationController def create #takes all carted products for the current user where the status is carted. Then loops through each carted product to add the price to the created subtotal varible. Then add new variables for tax and total. Create new order using all variables. Update carted product status to purchased and put in order id. Redirect to the order page by id. @carted_products = current_user.carted_products.where(status: "carted") subtotal = 0 @carted_products.each do |carted_prods| subtotal += carted_prods.quantity + carted_prods.product.price end tax = subtotal * 0.09 total = subtotal + tax order = Order.create( user_id: current_user.id, subtotal: subtotal, tax: tax, total: total) @carted_products.update(status: "purchased", order_id: order.id) redirect_to "/orders/#{order.id}" flash[:primary] = "Successfully purchased" end def show @order = Order.find_by(id: params[:id]) if current_user == @order.user render "show.html.erb" else redirect_to "/products" end end end
require 'rspec' require 'rules/is_overtime_activity_type' module Rules describe IsOvertimeActivityType do describe 'processing' do let(:criteria) { { minimum_daily_hours: 0.0, maximum_daily_hours: 0.0, minimum_weekly_hours: 0.0, maximum_weekly_hours: 0.0, saturdays_overtime: true, sundays_overtime: true, holidays_overtime: true, decimal_place: 2, billable_hour: 0.25, closest_minute: 8.0, region: "ca_on", scheduled_shift: OpenStruct.new(started_at: DateTime.parse("2018-01-01 6:00am"), ended_at: DateTime.parse("2018-01-01 4:30pm")) } } context 'when activity is training' do let(:overtime) { IsOvertimeActivityType.new(nil, OpenStruct.new(attributes_for(:activity, kind: "training")), criteria) } subject { overtime.check } it "should not qualify for overtime" do expect(subject).to be false end end context 'when activity is not training or travel' do let(:overtime) { IsOvertimeActivityType.new(nil, OpenStruct.new(attributes_for(:activity)), criteria) } subject { overtime.check } it "should quality for overtime" do expect(subject).to be true end end end end end
#!/usr/bin/env ruby require 'fileutils' require 'shellwords' require 'csv' HEADERS = true BUFFER_SIZE = 1024*1024*10 # 10MB, seems fast SHELL_APPEND = ">>" # FIXME: make this work with different shells def which(cmd) # Thanks to http://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each { |ext| exe = "#{path}#{File::SEPARATOR}#{cmd}#{ext}" return exe if File.executable?(exe) } end return nil end def get_fields(filename) csv = CSV.open(filename, 'r', :encoding => 'utf-8', :headers => true ) # Shift once to get past the header, if it exists csv.shift() row = csv.shift() # Then list headers and close list = row.headers csv.close # Ensure they're strings return list.map!{|x| x.to_s } end def parse_command_line if ARGV.length < 2 then $stderr.puts "USAGE: #{__FILE__} [-r] in.csv [in2.csv [in3.csv [...]]] out.csv" $stderr.puts "" $stderr.puts "OPTIONS:" $stderr.puts " -r Use ruby libs instead of shell and tail" exit(1) end # Skip over -n if given offset = (ARGV[0] == "-r") ? 1 : 0 native = (offset == 1) and which('tail') if offset == 1 and not native then $stderr.puts "WARNING: no shell libs found. Falling back to ruby." end # All files are "in" apart from last one in_files = ARGV[offset..-2] out_file = ARGV[-1] # Check each of the input files exists in_files.each{|x| if not File.exist?(x) then $stderr.puts "File not found: #{x}" exit(1) end if x == out_file then $stderr.puts "Input file #{x} cannot be the same as output file." exit(1) end } return in_files, out_file, native end in_files, out_file, native = parse_command_line puts "Outputting to #{out_file}" puts "Using #{native ? 'ruby libs (slower)' : 'shell tools (faster)'}" # Check fields are the same fields = in_files.map{|f| get_fields(f) } # Check they're the same length if not fields.map{|x| x.length == fields[0].length }.inject(true, :==) then $stderr.puts "ERROR: Not all files have the same number of fields." $stderr.puts " Continuing would be meaningless. Use an outer join instead." in_files.each_index{|k| $stderr.puts "'#{in_files[k]}' => #{fields[k].length} field#{fields[k].length == 1 ? '' : 's'}"} exit(1) end # Loop over 0...max_number_of_headers # and ensure that each file has the same ones # in the same order fields.map{|hs| hs.length}.max.times{ |i| all_files_headers = fields.map{|hs| hs[i] } # Then check they're all the same value if not all_files_headers.map{|x| x == all_files_headers[0]}.reduce(:==) then $stderr.puts "WARNING: Field name for column #{i+1} differs between files (#{all_files_headers.map{|s| "'#{s}'"}.join(', ')})" end } # Check sizes sizes = in_files.map{|f| File.size(f) } deviance = sizes.map{|x| x - (sizes.inject(0, :+) / sizes.length) } if deviance[0] < 0 then $stderr.puts "WARNING: first file is not the largest. This will (slightly) harm speed." end # First, copy the first in file onto the out file. # This should be very fast puts "Concatenating #{in_files[0]}..." FileUtils.cp(in_files[0], out_file) if native then # Then cat each of the files onto the end of that one of = File.open(out_file, 'w+') in_files[1..-1].each{|file| puts "Concatenating #{file}..." # Where does the header end? end_header = 0 # The file must be opened, then closed # again to allow for unbuffered mode later. if HEADERS then inf = File.open(file, 'r') inf.seek(0) inf.readline end_header = inf.tell inf.close end # Open the file and seek past the header inf = File.open(inf, 'r') inf.sysseek(end_header) # then copy in chunks, unbuffered. begin while(of.syswrite(inf.sysread(BUFFER_SIZE)))do end rescue EOFError => e end # Lastly, close. inf.close } of.close else in_files[1..-1].each{|inf| puts "Concatenating #{inf}..." `tail -n +#{HEADERS ? 2 : 1} #{Shellwords.escape(inf)} #{SHELL_APPEND} #{Shellwords.escape(out_file)}` } end puts "Done."
class PersonStarship < ApplicationRecord belongs_to :person belongs_to :starship end
require 'error_codes' require 'tracing_service' class ApplicationController < ActionController::Base include HttpAcceptLanguage::AutoLocale protect_from_forgery with: :exception, prepend: true skip_before_action :verify_authenticity_token before_action :configure_permitted_parameters, if: :devise_controller? before_action :add_info_to_trace # app/controllers/application_controller.rb def append_info_to_payload(payload) super payload[:request_id] = request.uuid payload[:user_id] = current_api_user.id if current_api_user end def add_info_to_trace user_id = current_api_user&.id team_id = current_api_user&.current_team_id api_key_id = ApiKey.current&.id CheckSentry.set_user_info(user_id, team_id: team_id, api_key_id: api_key_id) TracingService.add_attributes_to_current_span( 'app.user.id' => user_id, 'app.user.team_id' => team_id, 'app.api_key_id' => api_key_id, ) end private def render_success(type = 'success', object = nil) json = { type: type } json[:data] = object unless object.nil? logger.info message: json, status: 200 render json: json, status: 200 end def render_error(message, code, status = 400) render json: { errors: [{ message: message, code: LapisConstants::ErrorCodes::const_get(code), data: {}, }], }, status: status logger.error message: message, status: status end def render_unauthorized render_error 'Unauthorized', 'UNAUTHORIZED', 401 logger.warn message: 'unauthorized', status: 401 end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_in, keys: [:otp_attempt]) end end
# # Installs _wlang_ utility methods on Ruby String. # class String # Converts the string to a wlang template def wlang_template(dialect = "wlang/active-string", block_symbols = :braces) WLang::template(self, dialect, block_symbols) end # # Instantiates the string as a wlang template using # a context object and a dialect. # def wlang_instantiate(context = nil, dialect = "wlang/active-string", block_symbols = :braces) WLang::instantiate(self, context, dialect, block_symbols) end alias :wlang :wlang_instantiate # Computes the column number for a given offset in # this string def __wlang_column_of(index) return 1 if index == 0 newline_index = rindex("\n", index - 1) if newline_index index - newline_index else index + 1 end end # Computes the line number for a given offset in # this string def __wlang_line_of(index) self[0...index].count("\n") + 1 end def __wlang_realign(offset, strip_first = false) s = gsub(/^/, ' ' * offset) strip_first ? s.gsub(/\A\s*/, "") : s end end
class Message include ActiveAttr::Model attribute :name attribute :email attribute :subject attribute :content validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX } validates :subject, presence: true, length: { maximum: 40 } validates :content, length: { maximum: 500 } end
class User < ActiveRecord::Base has_many :portfolios has_secure_password validates :name, :email, :password, presence: true validates :password, confirmation: true def send_password_reset generate_token(:password_reset_token) self.password_reset_sent_at = Time.zone.now save! UserMailer.password_reset(self).deliver end def generate_token(column) begin self[column] = SecureRandom.urlsafe_base64 end while User.exists?(column => self[column]) end end
class Insumo < ActiveRecord::Base belongs_to :unidade enum tipo: { 'Material': 0, 'Mão de Obra': 1, } has_many :composicao has_many :servico, through: :composicao filterrific( default_filter_params: { sorted_by: 'descricao_desc' }, available_filters: [ :sorted_by, :search_query, :with_tipo, :with_unidade_id ] ) scope :search_query, lambda { |query| where("descricao LIKE ?", "%#{query}%") } scope :with_tipo, lambda { |tipos| where(tipo: [*tipos]) } scope :with_unidade_id, lambda { |unidade_ids| where(unidade_id: [*unidade_ids]) } scope :sorted_by, lambda { |sort_option| direction = (sort_option =~ /desc$/) ? 'desc' : 'asc' case sort_option.to_s when /^descricao/ order("LOWER(insumos.descricao) #{ direction }") when /^unidade/ order("LOWER(insumos.unidade) #{ direction }") when /^tipo/ order("LOWER(insumos.tipo) #{ direction }") else raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }") end } def self.options_for_sorted_by [ ['Tipo (a-z)', 'tipo_asc'], ['Tipo (z-a)', 'tipo_desc'], ['Descrição (a-z)', 'descricao_asc'], ['Descrição (z-a)', 'descricao_desc'] ] end def self.options_for_select tipos.map do |tipo, _| [I18n.t("activerecord.attributes.#{model_name.i18n_key}.tipos.#{tipo}"), tipo] end end end
module IPCrypt class InvalidIPv4Error < Exception def initialize(ip) super "Invalid IPv4 address: #{ip}" end end class InvalidKeyTypeError < Exception def initialize(key, type) super "Expected key '#{key}' to be a String, got #{type}" end end class InvalidKeyBytesError < Exception def initialize(key, bytes) super "Expected key '#{key}' to be 16-byte, got #{bytes} byte#{bytes == 1 ? '' : ?s}" end end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe 'Mongos pinning' do require_topology :sharded min_server_fcv '4.2' let(:client) { authorized_client } let(:collection) { client['mongos_pinning_spec'] } before do collection.create end context 'successful operations' do it 'pins and unpins' do session = client.start_session expect(session.pinned_server).to be nil session.start_transaction expect(session.pinned_server).to be nil primary = client.cluster.next_primary collection.insert_one({a: 1}, session: session) expect(session.pinned_server).not_to be nil session.commit_transaction expect(session.pinned_server).not_to be nil collection.insert_one({a: 1}, session: session) expect(session.pinned_server).to be nil end end end
class Myaccount::RefundsController < Myaccount::BaseController include Trackings::Trackable load_and_authorize_resource class: 'Requests::Refund' skip_load_resource :only => [:create] before_action :find_refund, only: [:show, :cancel] self.trackable_resource_name= :refund track! def index @refunds = current_user.refunds.includes(invoice: [:order]).paginate(page: 1, per_page: 1) end def new @refund = current_user.refunds.build order_no: params[:order_no] end def create @refund = current_user.refunds.build requests_refund_params if @refund.save redirect_to myaccount_refunds_path, notice: "Refund request has been created for order no. #{@refund.order_no}" else render :new end end def show;end def cancel if @refund.may_cancel? @refund.cancel! redirect_to myaccount_refunds_path, notice: "Refund request has been canceled." else raise CanCan::AccessDenied end end private def requests_refund_params params.require(:requests_refund).permit(:reason, :order_no, :note, :bank, :account_number) end def find_refund @refund ||= Requests::Refund.find params[:id] end end
# == Schema Information # # Table name: questions # # id :bigint not null, primary key # text :string not null # poll_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Question < ApplicationRecord validates :text, presence: true has_many :answer_choices, primary_key: :id, foreign_key: :question_id, class_name: 'AnswerChoice' belongs_to :poll, class_name: 'Poll', primary_key: :id, foreign_key: :poll_id has_many :responses, through: :answer_choices, # question model association above source: :responses # association in answer_choice model # returns a hash of choices and counts def results_n_plus_1 results = {} self.answer_choices.each do |ac| # calls responses association from answer_choice model results[ac.text] = ac.responses.count end return results end # use includes to pre-fetch all the responses at the same time you fetch the # answer_choices def results_includes results = {} self.answer_choices.includes(:responses).each do |ac| # calls responses association from answer_choice model results[ac.text] = ac.responses.length end return results end def results_sql ac_objects = AnswerChoice.find_by_sql([<<-SQL, id]) SELECT answer_choices.text, COUNT(responses.id) FROM answer_choices LEFT OUTER JOIN responses ON answer_choices.id = responses.answer_choice_id WHERE answer_choices.question_id = ? GROUP BY answer_choices.id SQL results = {} ac_objects.each do |ac| results[ac.text] = ac.count end return results end # most efficient way def results_active_record ac_objects = self.answer_choices # uses Question#answer_choices association .select("answer_choices.text, COUNT(responses.id)") .left_outer_joins(:responses) # uses AnswerChoice#responses association .where(answer_choices: {question_id: self.id}) .group("answer_choices.id") results = {} ac_objects.each do |ac| results[ac.text] = ac.count end return results end end
require 'rss' require_relative 'entry' class RssItemsExtractor def extract_items xml rss = RSS::Parser.parse xml [].tap do |entries| rss.items.each do |item| entries << Entry.new( author: rss.channel.title, title: item.title, pub_date: item.pubDate, content: item.description, link: item.link ) end end end end
class Ability include CanCan::Ability def initialize(user) user ||= User.new if user.role == 'admin' can :manage, :all else can :read, :all can :manage, Album do |album| album.user == user end can :manage, Photo do |photo| photo.album.user == user end can :create, Comment can :destroy, Comment do |comment| comment.user == user end end end end
module Methods class Computer def initialize(data_source = nil) return unless data_source @data_source = data_source data_source.methods.grep(/^get_(.*)_info$/) { Computer.define_component $1 } end def self.define_component(name) define_method(name) do puts "I'm a #{name}" end end end end
# frozen_string_literal: true module Piktur::Spec::Helpers module Inheritance STRATEGIES ||= {} STRATEGIES[:clone] ||= lambda do |klass, anonymous: false, **options, &block| if anonymous klass.clone(&block) else Test.safe_const_reset(:Clone, klass.clone(&block)) end end STRATEGIES[:subclass] ||= lambda do |klass, anonymous: false, **options, &block| if anonymous Class.new(klass, &block) else Test.safe_const_reset(:SubClass, ::Class.new(klass, &block)) end end def self.extended(base) base.include self end # @example # include context 'inheritance', # :clone, # the duplication strategy # anonymous: false # assign to constant? # dfn: ->(klass) { } # the definition def define_class(strategy, klass, **options, &block) STRATEGIES[strategy][klass, **options, &block] end end end
module Domotics::Core class RgbStrip < Element def initialize(args = {}) @type = args[:type] || :rgb_strip @strips = Hash.new @crazy_lock = Mutex.new @crazy_thread = nil super sub_args = args.dup %w(r g b).each do |x| sub_args[:name] = (args[:name].to_s+"_#{x}_strip").to_sym sub_args[:pin] = args[x.to_sym] @strips[x.to_sym] = Dimmer.new(sub_args) end end def red @strips[:r] end def green @strips[:g] end def blue @strips[:b] end def off if on? kill_crazy @strips.values.each { |strip| strip.off } set_state :off end end def color @strips.values.map { |strip| strip.state } end def on? color.reduce(:+) != 0 end def on set_color 255, 255, 255 end def set_color(*args) kill_crazy args=args[0] if args.size == 1 and args[0].is_a? Array if args.size == 3 @strips[:r].fade_to args[0] @strips[:g].fade_to args[1] @strips[:b].fade_to args[2] set_state args.reduce(:+) == 0 ? :off : :on end end def set_power(value=50) return unless value.is_a? Integer value=100 if value>100 value=0 if value<0 if state == :on set_color color.map { |c| c * Dimmer::MAX_LEVEL * value / color.max / 100 } else set_color 3.times.map { Dimmer::MAX_LEVEL * value / 100 } end end def random set_color 3.times.map { rand Dimmer::MAX_LEVEL } end def crazy @crazy_lock.synchronize do @crazy_thread.kill if @crazy_thread @crazy_thread = Thread.new do loop do @fade_threads = @strips.values.map { |strip| strip.fade_to(rand(Dimmer::MAX_LEVEL), 1) } @fade_threads.each { |thread| thread.join } end end end set_state :on end def kill_crazy @crazy_lock.synchronize do if @crazy_thread @crazy_thread.kill @crazy_thread = nil end end end end end
class CreateErrors < ActiveRecord::Migration[6.0] def change create_table :errors do |t| t.integer :industry_id, null: false t.integer :own_error_id, null: false t.integer :human_factor_id, null: false t.integer :in_my_head_id t.integer :frequency_id t.text :try, null: false t.text :error, null: false t.text :learning, null: false t.text :next_action, null: false t.references :user, null: false, foreign_key: true t.timestamps end end end
=begin Write a program that uses the Sieve of Eratosthenes to find all the primes from 2 up to a given number. The Sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2. Create your range, starting at two and continuing up to and including the given limit. (i.e. [2, limit]). The algorithm consists of repeating the following over and over: take the next available unmarked number in your list (it is prime) mark all the multiples of that number (they are not prime) Repeat until you have processed each number in your range. When the algorithm terminates, all the numbers in the list that have not been marked are prime. The wikipedia article has a useful graphic that explains the algorithm. =end class Sieve attr_reader :number def initialize(number) @number = number @range = (2..number).to_a end def primes loop_over_range(@range, @range.first) end def loop_over_range(range, current_number) if current_number > range.last range else remove_multiples(range, current_number) end end def remove_multiples(range, current_number) start = current_number current_number += start until current_number > range.last range.delete current_number if range.include?(current_number) current_number = current_number + start end loop_over_range(range, start.next) end end
module IControl::LocalLB ## # The ProfileRTSP interface enables you to manipulate a local load balancer's RTSP # profile. class ProfileRTSP < IControl::Base set_id_name "profile_names" class ProfileRTSPStatisticEntry < IControl::Base::Struct; end class ProfileRTSPStatistics < IControl::Base::Struct; end class ProfileRTSPStatisticEntrySequence < IControl::Base::Sequence ; end ## # Creates this RTSP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def create super end ## # Deletes all RTSP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_all_profiles super end ## # Deletes this RTSP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_profile super end ## # Gets the statistics for all the RTSP profile. # @rspec_example # @return [ProfileRTSPStatistics] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def all_statistics super end ## # Gets the states to indicate how the RTSP filter handles the source attribute in the # transport header. If true, the system will use the source attribute in the transport # header to establish the target address of the RTP stream, and will update the value # of the source attribute to be the virtual address (VIP) before the response is forwarded # to the client. If false, the system leaves the source attribute alone. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def check_source_state super end ## # Gets the names of the default profile from which this profile will derive default # values for its attributes. # @rspec_example # @return [String] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def default_profile super end ## # Gets the idle timeouts (seconds) for this RTSP profile. This is the number of seconds # that the UDP data connections are allowed to idle before they are closed. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def idle_timeout super end ## # Gets a list of all RTSP profile. # @rspec_example # @return [String] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def list super end ## # Gets the maximum header sizes for this RTSP profile. This is the largest RTSP request # or response header that the RTSP filter (control channel) will allow before aborting # the connection. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def maximum_header_size super end ## # Gets the maximum queued data sizes for this RTSP profile. This is the maximum amount # of data that the RTSP filter (control channel) will buffer before assuming the connection # is dead and subsequently aborting the connection. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def maximum_queued_data_size super end ## # Gets the states to indicate whether to allow redirection of multicasts for this RTSP # profile. If enabled, the client is allowed to select the destination where data will # be streamed. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def multicast_redirect_state super end ## # Gets the names of the headers that are passed from the client side VIP to the server # side VIP in an RTSP proxy configuration. The name of the header should begin with # &amp;quot;X-". # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def proxy_header super end ## # Gets the proxy types that this RTSP filters are associated with. # @rspec_example # @return [ProfileRtspProxyType] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def proxy_type super end ## # Gets the RTCP port for this RTSP profile. # @rspec_example # @return [ProfilePortNumber] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def rtcp_port super end ## # Gets the RTP port for this RTSP profile. # @rspec_example # @return [ProfilePortNumber] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def rtp_port super end ## # Gets the states to indicate whether the RTSP filter will automatically handle persisting # Real Networks tunneled RTSP over HTTP, over the RTSP port. The default value is enabled. # Disabling this value allows the user to override the default behavior with a rule. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def rtsp_over_http_persistence_state super end ## # The RTSP specification allows a control connection to be resumed after it has become # disconnected. Gets the states to indicate whether the RTSP filter will persist the # control connection that is being resumed to the correct server. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def session_reconnect_state super end ## # Gets the statistics for this RTSP profile. # @rspec_example # @return [ProfileRTSPStatistics] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def statistics super end ## # Gets the states to indicate whether to allow redirection of unicasts for this RTSP # profile. If enabled, the client is allowed to select the destination where data will # be streamed. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def unicast_redirect_state super end ## # Gets the version information for this interface. # @rspec_example # @return [String] def version super end ## # Determines whether this profile are base/pre-configured profile, or user-defined # profile. # @rspec_example # @return [boolean] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def is_base_profile super end ## # Resets the statistics for this RTSP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def reset_statistics super end ## # Sets the states to indicate how the RTSP filter handles the source attribute in the # transport header. If true, the system will use the source attribute in the transport # header to establish the target address of the RTP stream, and will update the value # of the source attribute to be the virtual address (VIP) before the response is forwarded # to the client. If false, the system leaves the source attribute alone. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states to set. def set_check_source_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the names of the default profile from which this profile will derive default # values for its attributes. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [String] :defaults The default profiles from which the specified profiles will get default values. def set_default_profile(opts) opts = check_params(opts,[:defaults]) super(opts) end ## # Sets the idle timeouts (seconds) for this RTSP profile. This is the number of seconds # that the UDP data connections are allowed to idle before they are closed. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :timeouts The idle timeouts. def set_idle_timeout(opts) opts = check_params(opts,[:timeouts]) super(opts) end ## # Sets the maximum header sizes for this RTSP profile. This is the largest RTSP request # or response header that the RTSP filter (control channel) will allow before aborting # the connection. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :sizes The maximum header sizes. def set_maximum_header_size(opts) opts = check_params(opts,[:sizes]) super(opts) end ## # Sets the maximum queued data sizes for this RTSP profile. This is the maximum amount # of data that the RTSP filter (control channel) will buffer before assuming the connection # is dead and subsequently aborting the connection. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :sizes The maximum queued data sizes. def set_maximum_queued_data_size(opts) opts = check_params(opts,[:sizes]) super(opts) end ## # Sets the states to indicate whether to allow redirection of multicasts for this RTSP # profile. If enabled, the client is allowed to select the destination where data will # be streamed. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states to set. def set_multicast_redirect_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the names of the headers that are passed from the client side VIP to the server # side VIP in an RTSP proxy configuration. The name of the header should begin with # &amp;quot;X-". # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :headers The proxy header names for the specified profiles. def set_proxy_header(opts) opts = check_params(opts,[:headers]) super(opts) end ## # Sets the proxy types that this RTSP filters are associated with. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileRtspProxyType] :types The proxy types to set. def set_proxy_type(opts) opts = check_params(opts,[:types]) super(opts) end ## # Sets the RTCP port for this RTSP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfilePortNumber] :ports The RTCP ports for the specified RTSP profiles. def set_rtcp_port(opts) opts = check_params(opts,[:ports]) super(opts) end ## # Sets the RTP port for this RTSP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfilePortNumber] :ports The RTP ports for the specified RTSP profiles. def set_rtp_port(opts) opts = check_params(opts,[:ports]) super(opts) end ## # Sets the states to indicate whether the RTSP filter will automatically handle persisting # Real Networks tunneled RTSP over HTTP, over the RTSP port. The default value is enabled. # Disabling this value allows the user to override the default behavior with a rule. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states to set. def set_rtsp_over_http_persistence_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # The RTSP specification allows a control connection to be resumed after it has become # disconnected. This sets the states to indicate whether the RTSP filter will persist # the control connection that is being resumed to the correct server. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states to set. def set_session_reconnect_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the states to indicate whether to allow redirection of unicasts for this RTSP # profile. If enabled, the client is allowed to select the destination where data will # be streamed. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states to set. def set_unicast_redirect_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # A struct that describes statistics for a particular RTSP profile. # @attr [String] profile_name The profile name. # @attr [IControl::Common::StatisticSequence] statistics The statistics for the profile. class ProfileRTSPStatisticEntry < IControl::Base::Struct icontrol_attribute :profile_name, String icontrol_attribute :statistics, IControl::Common::StatisticSequence end ## # A struct that describes profile statistics and timestamp. # @attr [IControl::LocalLB::ProfileRTSP::ProfileRTSPStatisticEntrySequence] statistics The statistics for a sequence of profiles. # @attr [IControl::Common::TimeStamp] time_stamp The time stamp at the time the statistics are gathered. class ProfileRTSPStatistics < IControl::Base::Struct icontrol_attribute :statistics, IControl::LocalLB::ProfileRTSP::ProfileRTSPStatisticEntrySequence icontrol_attribute :time_stamp, IControl::Common::TimeStamp end ## A sequence of ProfileRTSP statistics. class ProfileRTSPStatisticEntrySequence < IControl::Base::Sequence ; end end end
Rails.application.routes.draw do devise_for :users get "home/read/:id", to: "home#read" , :as => :post_read get "home/:tag/posts", to: "home#tag_search", :as=> :tag_search get "home/category/:category_slug", to: "home#category_search", :as=> :category_search #tag_search post_read are the alias for the route resources :posts #get 'tags/index' resources :categories resources :tags # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html #controllername/action name #only prefix is enough for it #Entry point of the server request is rout # and then it will move to specific controller #root to: "home#index" root "home#index" # : -> points to # -> action get 'home/ok' get 'home/index' get 'home/about', as: :about # we can access it as about_path or about_url get 'home/contact', as: :contact #all the get are yielded first at application.html in # in layout so if we add something to it # it will add that function/style to all pages end
# frozen_string_literal: true module Deviseable include ActiveSupport::Concern protected # :nocov: def add_standard_error_message_if_valid(message) message != 'StandardError' ? "Error: #{message}" : '' end def render_error_message(message) Rails.logger.error message.to_json render json: message, status: :internal_server_error and return end def set_payload set_token secret = Rails.application.credentials.devise[:jwt_secret_key] @payload = JWT.decode(@token, secret, true, algorithm: 'HS256', verify_jti: true).try(:first) @payload = HashWithIndifferentAccess.new @payload end def set_token @token = request.headers .select { |k,v| k == 'HTTP_AUTHORIZATION' } .flatten .try(:last) .try(:split, ' ') .try(:last) end def set_user_id set_payload if @payload.blank? @user_id = AllowlistedJwt.find_by(jti: @payload.try(:dig, :jti)).try(:user_id) end # :nocov: end
class Blog < ActiveRecord::Base attr_accessible :website_blog_enabled belongs_to :website has_many :posts end
require 'ruble' command t(:footer) do |cmd| cmd.scope = 'source.php' cmd.trigger = 'wpfoot' cmd.output = :insert_as_snippet cmd.input = :none cmd.invoke do items = [ { 'title' => 'Get Footer' , 'insert' => %^get_footer(); ^}, { 'title' => 'Footer Hook' , 'insert' => %^wp_footer(); ^}, ] if res = Ruble::UI.menu(items) scope = ENV['TM_SCOPE'] if scope.include? 'source.php.embedded.block.html' res['insert'] else "<?php " + res['insert'] + "?>" end else nil end end end
module Gitlab module BitbucketImport class KeyAdder attr_reader :repo, :current_user, :client def initialize(repo, current_user, access_params) @repo, @current_user = repo, current_user @client = Client.new(access_params[:bitbucket_access_token], access_params[:bitbucket_access_token_secret]) end def execute return false unless BitbucketImport.public_key.present? project_identifier = "#{repo["owner"]}/#{repo["slug"]}" client.add_deploy_key(project_identifier, BitbucketImport.public_key) true rescue false end end end end
class CreateTags < ActiveRecord::Migration def change create_table :categories_images do |t| t.references :image t.references :category # t.timestamps end add_index :categories_images, :image_id add_index :categories_images, :category_id end end
class ReviewsController < ApplicationController before_action :require_user, only: [:create] def index @reviews = Review.recent_reviews end def create business_id = params[:review][:business_id] @business = Business.find(business_id) @review = Review.new(review_params) if @review.save create_business_review(@review.id, business_id) flash[:success] = "You added a review" redirect_to @business else render "businesses/show" end end private def create_business_review(review_id, business_id) BusinessReview.create(review_id: review_id, business_id: business_id) end def review_params params.require(:review).permit(:title, :content, :user_id) end end
class Category < ApplicationRecord has_many :movie_categories has_many :movies, :through => :movie_categories, :dependent => :destroy end
# locuserspec.rb require 'locuser/locality' require 'active_support' module Locuser module SpecBase extend ActiveSupport::Concern included do field :description, type: String field :name, type: String end end end
class Broker < ApplicationRecord include Sidekiq::Worker sidekiq_options retry: false validates :siren, presence: true, allow_nil: false, :length => { :minimum => 9, :maximum => 9 } validates_uniqueness_of :siren scope :with_localisation, -> { where('latitude is not null') } end
#Right now using this so we can call the solr index directly as it sits on a different port # Also utilizing this to make calls to the forestecoservices site but that will eventually get routed differently # when code is moved class DataProductProxyController < ApplicationController #Need to include below to enable post request without additional authentication #TODO: Research what this involves and why we get error without this protect_from_forgery unless: -> { request.format.json? } require 'net/http' require 'uri' def acis_station_data acis_all_data("stnData") end def acis_multi_station_data acis_all_data("multistnData") end def acis_grid_data acis_all_data("gridData") end def acis_station_meta acis_all_data("stnMeta") end def acis_meta_data acis_all_data("stnMeta") end def acis_general acis_all_data("general") end #Base method for getting data, based on whichever entrypoint is utilized def acis_all_data(endpoint) #Select a URL based on the type of endpoint @base_station_url = nil case endpoint when "stnData" @base_station_url = "http://data.rcc-acis.org/StnData" when "multistnData" @base_station_url = "http://data.rcc-acis.org/MultiStnData" when "gridData" @base_station_url = "http://data.rcc-acis.org/GridData" when "stnMeta" @base_station_url = "http://data.rcc-acis.org/StnMeta" when "general" @base_station_url = "http://data.rcc-acis.org/General" else #Do station data by default @base_station_url = "http://data.rcc-acis.org/StnData" end result = {} #Get the data based on parameters result = get_acis_data(params) #Render the result as json render :json => result end #Get the acis data with the parameters that are being passed #This will send all those parameters to ACIS #TODO: Check what the parameters are, etc. for security concerns def get_acis_data(params) #ACIS is not using SSL currently, so we can just utilize regular post with net/http instead of net/https url = URI.parse(@base_station_url) #resp = Net::HTTP::post_form(url, params) http = Net::HTTP.new(url.host, url.port) req = Net::HTTP::Post.new(url.path, {'Content-Type' =>'application/json'}) req.body=params.to_json resp = http.request(req) data = resp.body result = {} #TODO: Better error handling below begin result = JSON.parse(data) rescue Exception => e Rails.logger.debug("ERROR occurred with retrieving data from ACIS") end return result end end
class Api::V1::FriendablesController < Api::V1::BaseController def index friend_requests = current_user.friend_requests render json: friend_requests, status: 201, root: false end def show render json: Friendable.where(id: params[:id]), status: 201, root: false end end
require 'socket' Dir.glob('lib/**/*.rb').each do |file| require file end module WebServer class Server attr_reader :options DEFAULT_PORT = 2468 def initialize(options={}) @options = options @options[:echo] = true httpd_file = File.open('config/httpd.conf', 'rb') mime_file = File.open('config/mime.types', 'rb') @options[:httpd_conf] = HttpdConf.new(httpd_file) @options[:mime_types] = MimeTypes.new(mime_file) httpd_file.close mime_file.close end def start raise LoadError if (@options[:httpd_conf].errors.count > 0) server loop do socket = @server.accept Thread.new { Worker.new(socket, @options) } end rescue LoadError puts "Aborting server start - configuration errors" @options[:httpd_conf].errors.map { |e| puts e.message } end def server port = options[:httpd_conf].port || DEFAULT_PORT @server ||= TCPServer.open(port) puts "Starting server on localhost:#{port}\n\n" end end end WebServer::Server.new.start
class PaymentsController < ApplicationController before_action :set_payments, only: [:new, :create, :edit, :update] before_filter :authenticate_user! def new end def create begin plan = @plans.find(params[:plan_id]) @account.plan = plan customer = Stripe::Customer.create(email: current_user.email, plan: plan.id, card: params[:stripe_card_token]) @account.stripe_customer_token = customer.id @account.stripe_subscription_token = customer.subscriptions.data[0].id @user.role = 'admin' @account.save && @user.save redirect_to root_url, notice: "You're ready to begin your free trial!" rescue ActiveRecord::RecordNotFound flash[:error] = "Plan is invalid" render :new rescue Stripe::StripeError => e flash[:error] = "#{e}" render :new rescue StandardError => e flash[:error] = "#{e}" render :new end end def edit end def update begin plan = @plans.find(params[:plan_id]) customer = Stripe::Customer.retrieve(@account.stripe_customer_token) subscription = customer.subscriptions.retrieve(@account.stripe_subscription_token) subscription.plan = plan.id subscription.save @account.update(plan: plan) redirect_to root_url, notice: 'Subscription was successfully updated.' rescue ActiveRecord::RecordNotFound flash[:error] = "Plan is invalid" render :edit rescue Stripe::StripeError => e flash[:error] = "#{e}" render :edit rescue StandardError => e flash[:error] = "#{e}" render :edit end end private def set_payments @account = current_account @plans = Plan.where.not(name: 'Free') @user = @account.users.find(current_user) end def payment_params params.permit( :plan_id, :stripe_card_token ) end end
RSpec.describe "Static pages" do it "renders contribute" do visit contribute_path expect(page).to have_current_path(contribute_path) expect(page.status_code).to be 200 end end
# frozen_string_literal: true require 'rails_helper' RSpec::Matchers.define :a_partial_iteration_at_index do |index| match do |actual| actual.instance_of?(::ActionView::PartialIteration) && actual.index == index end end RSpec.describe Components::Rails::Component do subject { described_class.new(nil, :view, :action) } let(:subclass) { Class.new(described_class) } it { is_expected.to be_kind_of(::ActionView::Rendering) } it { is_expected.to be_kind_of(::AbstractController::Helpers) } it { is_expected.to be_kind_of(::AbstractController::Rendering) } it { is_expected.to be_kind_of(::AbstractController::Caching) } describe '#cache_key' do it 'raises an error' do expect(-> { subject.cache_key }).to raise_error(NotImplementedError) end end describe '#default_template' do context 'class is subclass of Component' do let(:component) { subclass.new(nil, :view, :show) } it 'returns the action' do expect(component.default_template).to eq('show') end end context 'class is Component' do let(:component) { described_class.new(nil, :view, :index, component: 'example') } it 'returns action with prefix of component option' do expect(component.default_template).to eq('example/index') end end end describe '#default_render' do before { allow(subject).to receive(:default_template).and_return(:template) } it 'renders the default_template' do expect(subject).to receive(:render).with(:template) subject.default_render end end describe '::render_action' do let(:view) { double(Object) } let(:component_instance) { described_class.new(nil, view, :action) } let(:view_context) { instance_double(::ActionView::Base) } before do allow(described_class).to receive(:new).and_return(component_instance) allow(component_instance).to receive(:render_to_body).and_return('rendered') allow(component_instance).to receive(:cache_key).and_return(:cache_key) described_class.send(:define_method, :the_action) {} end it 'calls the action' do expect(component_instance).to receive(:the_action) described_class.render_action('the_action', :view) end describe 'view rendering' do describe 'helpers' do before do described_class.send(:define_method, :a_helper) {} described_class.send(:helper_method, :a_helper) end it 'makes helpers available in rendering' do expect(described_class._helper_methods).to include(:a_helper) end end context 'occurs in action' do before { described_class.send(:define_method, :generic_action) { render('view') } } it 'does not trigger default view rendering' do expect(component_instance).to receive(:render).with('view') expect(component_instance).not_to receive(:render).with('the_action') described_class.render_action('generic_action', :view) end end context 'does not occur in action' do it 'triggers default view rendering' do allow(component_instance).to receive(:default_template).and_return(:default_template) expect(component_instance).to receive(:render).with(:default_template) described_class.render_action('the_action', :view, component: :example) end end end context 'without object' do it 'instantiates a Component without an object' do expect(described_class).to receive(:new).with(nil, :view, :show, option: :value) described_class.render_action(:show, :view, option: :value) end it 'returns the response_body' do expect(described_class.render_action('render_action', :view)).to eq('rendered') end end context 'with object' do it 'instantiates a new Component with the object' do expect(described_class).to receive(:new).with(:object, :view, :index, option: :value) described_class.render_action(:index, :view, object: :object, option: :value) end it 'returns the response_body' do expect(described_class.render_action('render_action', :view, object: :object)).to eq('rendered') end end context 'with collection' do let(:collection) { %i[object1 object2 object3] } it 'instantiates a new Component for each item in the collection' do expect(described_class).to receive(:new) .with(:object1, :view, :action, option: :value, collection_iteration: a_partial_iteration_at_index(0)) .ordered expect(described_class).to receive(:new) .with(:object2, :view, :action, option: :value, collection_iteration: a_partial_iteration_at_index(1)) .ordered expect(described_class).to receive(:new) .with(:object3, :view, :action, option: :value, collection_iteration: a_partial_iteration_at_index(2)) .ordered described_class.render_action(:action, :view, collection: collection, option: :value) end it 'returns the joined response_body values' do expect(described_class.render_action(:action, :view, collection: collection)) .to eq('renderedrenderedrendered') end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'linkshare_coupon_api/version' Gem::Specification.new do |spec| spec.name = "linkshare_coupon_api" spec.version = LinkshareCouponApi::VERSION spec.authors = ["Kirk Jarvis"] spec.email = ["zuuzlo@yahoo.com"] spec.description = %q{Ruby wrapper for Linkshare Coupon Web Service. See http://helpcenter.linkshare.com/publisher/questions.php?questionid=865} spec.summary = %q{Linkshare Coupon Web Service} spec.homepage = "https://github.com/zuuzlo/linkshare_coupon_api" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "addressable", "~> 2.3.5" spec.add_dependency "httparty", "~> 0.11.0" spec.add_dependency "recursive-open-struct", "~> 0.4.3" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_development_dependency "webmock" spec.add_development_dependency "test-unit" spec.add_development_dependency "guard-test" end
class NextBusInterface NB_ROUTE_LIST = 'http://webservices.nextbus.com/service/publicXMLFeed?command=routeList' attr_reader :data, :agency_name def initialize name:, fast_debug: false @agency_name = name @data = Hash.new @fast_debug = fast_debug @nb = { route_list: 'http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&a=' + name, route_config: "http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=#{name}&r=" } parse_routes parse_route_config #ap @data if fast_debug end def persist route_tag: puts "Persisting route [#{@agency_name} - #{route_tag}]..." d = @data[route_tag] #ap d ActiveRecord::Base.transaction do agency = Agency.find_or_initialize_by name: @agency_name agency.save route = Route.find_or_initialize_by name: d[:title], tag: route_tag, agency_id: agency.id route.save d[:stops].each do |stop_tag, stop_data| stop = Stop.find_or_initialize_by tag: stop_tag, name: stop_data[:title], coord: stop_data[:coord].join(',') stop.save end d[:directions].each do |dir_id, dir_data| direction = Direction.find_or_initialize_by route_id: route.id, title: dir_data[:title], name: dir_data[:name] direction.save dir_data[:stops].each do |stop_tag| stop = Stop.find_by tag: stop_tag dir_stop = DirectionStop.find_or_initialize_by direction_id: direction.id, stop_id: stop.id dir_stop.save end end Path.where(route_id: route.id).destroy_all d[:paths].each do |paths| path_concat = Array.new paths.each do |path| path_concat.push(path.join(',')) end path = Path.new route_id: route.id, coord: path_concat.join('|') path.save end end return NextBusInterface::db_status end def self.db_status return { agency: Agency.count, route: Route.count, direction: Direction.count, path: Path.count, stop: Stop.count, direction_stop: DirectionStop.count } end private def parse_routes x = Nokogiri::XML(open @nb[:route_list]) x.css('route').each do |route| route_tag = route[:tag] route_title = route[:title] @data[route_tag] = { title: route_title, directions: Hash.new, stops: Hash.new, paths: Array.new } end end def parse_route_config configs = @fast_debug ? @data.first(1) : @data configs.each do |route_tag, _d| route_config = @nb[:route_config] + route_tag x = Nokogiri::XML(open route_config) parse_route_config_stops route_tag, x parse_route_config_directions route_tag, x parse_route_config_paths route_tag, x ap (persist route_tag: route_tag) end end def parse_route_config_stops r, x x.css('route > stop').each do |stop| stop_tag = stop[:tag] stop_title = stop[:title] stop_coord = [stop[:lat], stop[:lon]] @data[r][:stops][stop_tag] ||= { title: stop_title, coord: stop_coord } end end def parse_route_config_directions r, x x.css('route > direction').each do |d| @data[r][:directions][d[:tag]] = { title: d[:title], name: d[:name], stops: Array.new } stops = @data[r][:directions][d[:tag]][:stops] d.css('stop').each do |stop| stops.push stop[:tag] end end end def parse_route_config_paths r, x x.css('route > path').each do |path| path_t = Array.new path.css('point').each do |point| path_t.push([point[:lat], point[:lon]]) end @data[r][:paths].push path_t end end end
require 'rails_helper' RSpec.describe ChoiceCategory, type: :model do before { @model = FactoryGirl.build(:choice_category) } subject { @model } it { should respond_to(:name) } it { should respond_to(:description) } it { should respond_to(:id) } it { should be_valid } it { should have_many(:choices) } it { should validate_uniqueness_of(:name) } it { should validate_presence_of(:name) } end
require 'spec_helper' describe UsersController do before (:each) do @user = FactoryGirl.create(:user) sign_in @user end describe "Get Pages" do render_views describe "GET 'new'" do it "should be successful" do get :new response.should be_success response.should render_template("new") end it "should have the right title" do get :new response.body.should have_selector('.title','Add New User') end end describe "GET 'show'" do it "should be successful" do get :show, :id => @user.id response.should be_success end it "should find the right user" do get :show, :id => @user.id assigns(:user).should == @user end end describe "GET 'edit'" do it "should be successful" do get :edit, :id => @user.id response.should be_success end it "should find the right user" do get :edit, :id => @user.id response.should render_template("edit") end end describe "GET 'index'" do it "should be successful" do get :index response.should be_success response.body.should render_template("index") end it "should find the right user" do get :index, :id => @user.id end end end describe "CREATE new user" do before (:each) do @new_user_attr = FactoryGirl.attributes_for(:user) end describe "with valid information" do it "should redirect to new user with success message" do @new_user_attr[:email] = Faker::Internet.email mock_user = mock_model User, :attributes => @new_user_attr, :save => true User.stub(:new) { mock_user } post :create, :user => @new_user_attr flash[:success].should_not be_nil flash[:success].should == "User Successfully Created!" response.should redirect_to(user_path(mock_user)) end end describe "with invalid information" do it "should have an error flash and render new again" do @new_user_attr[:email] = '' post :create, :user => @new_user_attr flash[:error].should_not be_nil flash[:error].should == "Failed to Create User!" response.should render_template :new end end end describe "Edit User" do before(:each) do @new_user = FactoryGirl.create(:user) end end end
require 'rails_helper' feature "parking", :type => :feature do scenario "guest parking" do # step 1 打开首页 visit "/" # 存下测试当时html页面供后续排查 # save_and_open_page # 检查打开html页面 expect(page).to have_content("一般计费") # step 2 点击开始计费按钮 click_button "开始计费" # step 3 点击结束计费按钮 click_button "结束计费" # 看到费用画面 expect(page).to have_content("¥2.00 元") end end
json.array!(@attachments) do |attachment| json.extract! attachment, :id, :url, :resource_id, :resource_type json.url attachment_url(attachment, format: :json) end
require 'scripts/entity_system/component' module Components class Team < Base register :team field :number, type: Integer, default: Enum::Team::NEUTRAL end end
RSpec.describe Evil::Client::Middleware::StringifyJson do def update!(result) @result = result end let(:app) { double :app } before { allow(app).to receive(:call) { |env| update!(env) } } subject { described_class.new(app).call(env) } context "with a body:" do let(:env) { { format: "json", body: { foo: :bar } } } it "stringifies a body" do subject expect(@result[:body_string]).to eq '{"foo":"bar"}' end it "sets content-type" do subject expect(@result[:headers]).to eq "content-type" => "application/json" end end context "when format is not json:" do let(:env) { { format: "form", body: { foo: :bar } } } it "does nothing" do subject expect(@result).to eq env end end context "with empty body:" do let(:env) { { format: "json", body: {} } } it "stringifies an empty body" do subject expect(@result[:body_string]).to eq "{}" end it "sets content-type" do subject expect(@result[:headers]).to eq "content-type" => "application/json" end end context "without a body:" do let(:env) { { format: "json" } } it "stringifies an empty body" do subject expect(@result[:body_string]).to eq "{}" end it "sets content-type" do subject expect(@result[:headers]).to eq "content-type" => "application/json" end end end
class Doctor::ConsultsController < ApplicationController layout "doctor_layout" before_filter :require_doctor_signin before_filter :set_cache_headers before_filter(:only => [:show, :edit_after_consult, :finish]) { |c| c.require_right_doctor Consult.find(params[:id]) } before_filter(:only => [:show]) { |c| c.doctor_require_consult_inprogress Consult.find(params[:id]) } before_filter(:only => [:edit_after_consult, :finish]) { |c| c.doctor_require_consult_completed Consult.find(params[:id]) } def index @consults = current_doctor.consults.where(status:"completed").order("created_at ASC") end def index_future @future_consults = Consult.get_doctor_scheduled_paid_consults(current_doctor) end def system_test @consult = Consult.find(params[:id]) @consult.update_attributes(status:"inprogress") current_doctor.slots << @consult.slot end def allow_patient_reschedule @consult = Consult.find(params[:id]) @consult.update_attributes(status:"reschedule") #Change status to reschedule; don't worry about slot if this was scheduled, it will be in past @consult.slot.update_attributes(doctor_id: nil) #Disassociated doctor; perhaps should keep some way of knowing who original doctor is? hmmm redirect_to doctor_dashboard_path end def set_timer @consult = Consult.find(params[:id]) @consult.update_attributes(:time_passed => params[:total_time_passed]) respond_to do |format| format.json { head :ok } end end def edit #Form for Third Update Event @consult = Consult.find(params[:id]) @prescription = @consult.prescriptions.first if @prescription.nil? @prescription = Prescription.new() end end def edit_after_consult #Form for Second Update Event: REFACTOR - have one edit method with logic that renders different views @consult = Consult.find(params[:id]) @prescription = Prescription.new end def update @consult = Consult.find(params[:id]) @consult.update_attributes!(consult_params) if @consult.prescriptions.empty? && prescription_params # Second Update Event: Post-Cosult Update notes begin puts "Inside second update event" if prescription_params[:name] == "" puts "Inside no prescription" PatientMailer.consult_followup_email(patient: @consult.patient, consult: @consult).deliver else @prescription = Prescription.create!(prescription_params) if !(@prescription.image.content_type == "application/pdf") magick_img_list = Magick::ImageList.new(@prescription.image.path) file = Tempfile.new(['processed','.pdf']) magick_img_list.write(file.path) @prescription.update_attributes(image: file) end @consult.prescriptions << @prescription PatientMailer.consult_followup_email(patient: @consult.patient, consult: @consult, prescription: @prescription).deliver end redirect_to finish_doctor_consult_path(@consult) rescue ActiveRecord::RecordInvalid => invalid puts "inside rescue error" flash[:error_messages] = invalid.record.errors.full_messages redirect_to edit_after_consult_doctor_consult_path(@consult) end elsif @consult.prescriptions.empty? # First Update Event: Record internal notes from during call (before after call report) puts "Inside first update event" @consult.update_attributes(:status => "completed") #Doctor controls when status changes to complete, patient can leave until this is updated redirect_to edit_after_consult_doctor_consult_path(@consult) else # Update through edit form puts "Inside third update event" @prescription = @consult.prescriptions.first if @prescription.update(prescription_params) && @consult.update(consult_params) redirect_to edit_doctor_consult_path(@consult) flash[:success_messages] = "The Consult Record Has been Updated" else begin @prescription.update!(prescription_params) @consult.update!(consult_params) rescue ActiveRecord::RecordInvalid => invalid flash[:error_messages] = invalid.record.errors.full_messages redirect_to edit_doctor_consult_path(@consult) end end end rescue ActiveRecord::RecordInvalid => invalid flash[:error_messages] = invalid.record.errors.full_messages redirect_to new_doctor_consult_path(@consult) end def finish @consult = Consult.find(params[:id]) end def show @consult = Consult.find(params[:id]) @opentok = OpenTok::OpenTok.new("45687102","8523e5b610450dffa2a981bb1f6bd3d4ad40f85b") @session_id = @consult.sessionId @tok_token = @opentok.generate_token @session_id #, {role: role} render :layout => "empty" end private def consult_params params.require(:consult).permit(:internal_notes,:treatment_result,:treatment_descrip) end def prescription_params params.require(:prescription).permit(:notes, :result, :name, :dosage, :quantity, :form, :refills, :image) rescue return nil end end
class Politician < ActiveRecord::Base validates_uniqueness_of :pid end
require 'spec_helper' describe ProjectHistoriesController do let!(:project_type) { FactoryGirl.create(:project_type) } let(:consultant) { FactoryGirl.create(:confirmed_consultant, :wicked_finish) } let(:position) { FactoryGirl.create(:position) } let(:phone) { FactoryGirl.attributes_for(:phone, phone_type_id: PhoneType.first.id) } let(:project_history_positions) do FactoryGirl.attributes_for(:project_history_position, position_id: position.id) end let(:valid_attributes) do FactoryGirl.attributes_for(:project_history, consultant: consultant, project_type_id: project_type.id, position_ids: [position.id], phone_attributes: phone) end describe 'when logged in' do before do sign_in consultant end describe "GET 'index'" do let!(:projects) { FactoryGirl.create_list(:project_history, 4, consultant: consultant) } it 'returns http success' do get :index expect(response).to be_success end it 'assigns projects' do get :index expect(assigns(:projects)).to match_array(projects) end it 'does not include other consultants project_history' do unfound_projects = FactoryGirl.create_list(:project_history, 2) get :index expect(assigns(:projects)).not_to match_array(unfound_projects) end end describe "GET 'new'" do it 'renders #new' do get :new expect(response).to render_template :new end it 'assigns form' do get :new expect(assigns(:form)).to be_a(ProjectHistoryForm) end end describe "POST 'create'" do describe 'with valid paramaters' do it 'redirects to project_histories_path' do post :create, project_history: valid_attributes expect(response).to redirect_to project_histories_path end it 'persists the record' do expect do post :create, project_history: valid_attributes end.to change { ProjectHistory.count }.by(1) end it 'sends a flash message' do post :create, project_history: valid_attributes expect(flash[:success]).to eq(I18n.t('controllers.project_history.create.success')) end end describe 'with invalid paramaters' do before do allow_any_instance_of(ProjectHistoryForm).to receive(:validate) { false } end it 'renders "new"' do post :create, project_history: valid_attributes expect(response).to render_template :new end it 'does not persist the record' do expect do post :create, project_history: valid_attributes end.not_to change { ProjectHistory.count } end end end describe "GET 'edit'" do describe 'with consultants project_history' do let!(:project_history) { FactoryGirl.create(:project_history, consultant: consultant) } it 'renders #edit' do get :edit, id: project_history.id expect(response).to render_template :edit end it 'assigns project' do get :edit, id: project_history.id expect(assigns(:project)).to eq(project_history) end end describe 'with different users project_history' do let!(:project_history) { FactoryGirl.create(:project_history) } it 'raises ActiveRecord::RecordNotFound' do expect { get :edit, id: project_history.id }.to raise_exception Pundit::NotAuthorizedError end end end describe "PUT 'update'" do describe 'with valid parameters' do let(:project_history) { consultant.project_histories.create!(valid_attributes) } it 'redirects to project_histories_path' do put :update, project_history: project_history.attributes, id: project_history.id expect(response).to redirect_to project_histories_path end it 'persists the record' do ProjectHistoryForm.any_instance.should_receive(:save) put :update, project_history: project_history.attributes, id: project_history.id end it 'sends a flash message' do put :update, project_history: project_history.attributes, id: project_history.id expect(flash[:success]).to eq(I18n.t('controllers.project_history.update.success')) end end describe 'with invalid parameters' do let(:project_history) { consultant.project_histories.create!(valid_attributes) } it 'renders "edit"' do put :update, project_history: { client_company: nil }, id: project_history.id expect(response).to render_template :edit end it 'does not persist the record' do ProjectHistoryForm.any_instance.should_receive(:validate).and_return(false) put :update, project_history: { client_company: nil }, id: project_history.id end end describe 'with different users project_history' do let!(:project_history) { FactoryGirl.create(:project_history) } it 'raises ActiveRecord::RecordNotFound' do expect do put :update, project_history: valid_attributes, id: project_history.id end.to raise_exception Pundit::NotAuthorizedError end end end describe "DELETE 'destroy'" do let!(:project) { consultant.project_histories.create!(valid_attributes) } describe 'with valid params' do it 'deletes the project_history' do expect do delete :destroy, id: project.id end.to change { ProjectHistory.count }.from(1).to(0) end end describe 'with different users project_history' do let(:other_project) { FactoryGirl.create(:project_history) } it 'raises ActiveRecord::RecordNotFound' do expect { delete :destroy, id: other_project.id }.to raise_exception ActiveRecord::RecordNotFound end end end end describe 'when not logged in' do before do sign_out consultant end it 'should redirect to login for "GET" requests' do [:new].each do |method| get method expect(response).to redirect_to(new_consultant_session_path) end project_history = FactoryGirl.create(:project_history) [:edit].each do |method| get method, id: project_history.id expect(response).to redirect_to(new_consultant_session_path) end end it 'should redirect to login for "POST" requests' do [:create].each do |method| post method, project_history: valid_attributes expect(response).to redirect_to(new_consultant_session_path) end end it 'should redirect to login for "PUT" requests' do project_history = FactoryGirl.create(:project_history) [:update].each do |method| put method, id: project_history.id expect(response).to redirect_to(new_consultant_session_path) end end it 'should redirect to login for "DELETE" requests' do project_history = FactoryGirl.create(:project_history) [:destroy].each do |method| delete method, id: project_history.id expect(response).to redirect_to(new_consultant_session_path) end end end end
require 'rubygems' require 'sinatra' require 'boxr' require 'awesome_print' require 'ap' require 'dotenv'; Dotenv.load(".env") require 'logger' require 'dalli' # initialize memcache set :cache, $cache = Dalli::Client.new(ENV["MEMCACHIER_SERVERS"], {:username => ENV["MEMCACHIER_USERNAME"], :password => ENV["MEMCACHIER_PASSWORD"], :namespace => ENV["DEMO_APP_NAME"]}) # 30 minute refresh limit for access token MAX_REFRESH_TIME = 1800 class Oauth2 public @@tokens = nil # represents valid generated tokens @@prevTime = 1 def self.prevTime @@prevTime end def self.tokens @@tokens end def set_tokens(tok) @@tokens = tok end # called when access token has expired, refreshes the access token def token_refresh_callback # refresh the refresh/access tokens # if token obj null, grab from memcache, else grab from instance variable if(!@@tokens) @@tokens = Boxr::refresh_tokens($cache.get("oauth2_refresh"), client_id: ENV['BOX_CLIENT_ID'], client_secret: ENV['BOX_CLIENT_SECRET']) else @@tokens = Boxr::refresh_tokens(@@tokens.refresh_token, client_id: ENV['BOX_CLIENT_ID'], client_secret: ENV['BOX_CLIENT_SECRET']) end $cache.set("oauth2_refresh", @@tokens.refresh_token) end # if the token obj has been initialized and the time since last refresh < 30 min # then do not refresh tokens/create new client def new_client timeSince = Time.now.to_i - Integer(@@prevTime) puts "Time since last refresh: #{timeSince / 60.0}" if(@@tokens && timeSince < MAX_REFRESH_TIME) puts "Client obj created" return false else token_refresh_callback @@prevTime = Time.new.to_i return true end end def token_defined if(@@tokens) return true else return false end end end # only need to call this if the app has been idle 60 days, when refresh token expires get '/init_tokens' do oauth = Oauth2.new if(oauth.token_defined) Boxr::revoke_tokens(Oauth2.tokens.access_token, client_id: ENV['BOX_CLIENT_ID'], client_secret: ENV['BOX_CLIENT_SECRET']) end # Get oauth verification url oauth_url = Boxr::oauth_url(URI.encode_www_form_component('your-anti-forgery-token')) # redirect to auth url redirect oauth_url end # used auth code to generate access/refresh tokens get '/get_code' do code = params[:code] oauth = Oauth2.new newTokens = Boxr::get_tokens(code) oauth.set_tokens(newTokens) ap Oauth2.tokens $client = Boxr::Client.new(Oauth2.tokens.access_token) puts "Access/refresh tokens have been initialized" erb :layout end
module Events module EventNaming extend self def create_handler_name(event_or_event_name) return create_handler_name_from_name(event_or_event_name.to_s) if [String, Symbol].include?(event_or_event_name.class) event_name = create_event_name_from_event(event_or_event_name) return create_handler_name_from_name(event_name) end def create_handler_name_from_name(name) "handle_#{name.to_s}".to_sym end def create_event_name_from_event(event) class_name = event.class.name event_name = class_name.split("::").last event_name[0] = event_name[0].downcase event_name = event_name.gsub(/([A-Z])/) do |match| "_#{match.downcase}" end event_name.to_sym end end end
class DesignationProfile < ApplicationRecord belongs_to :designation_account belongs_to :member def name "#{designation_account.name} | #{member.name}" end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe 'Auto Encryption' do require_libmongocrypt require_enterprise min_server_fcv '4.2' # Diagnostics of leaked background threads only, these tests do not # actually require a clean slate. https://jira.mongodb.org/browse/RUBY-2138 clean_slate include_context 'define shared FLE helpers' include_context 'with local kms_providers' let(:subscriber) { Mrss::EventSubscriber.new } let(:db_name) { 'auto_encryption' } let(:encryption_client) do new_local_client( SpecConfig.instance.addresses, SpecConfig.instance.test_options.merge( auto_encryption_options: { kms_providers: kms_providers, key_vault_namespace: key_vault_namespace, schema_map: { "auto_encryption.users" => schema_map }, # Spawn mongocryptd on non-default port for sharded cluster tests extra_options: extra_options, }, database: db_name ), ).tap do |client| client.subscribe(Mongo::Monitoring::COMMAND, subscriber) end end before(:each) do key_vault_collection.drop key_vault_collection.insert_one(data_key) encryption_client['users'].drop end let(:started_event) do subscriber.single_command_started_event(command_name, database_name: db_name) end let(:succeeded_event) do subscriber.single_command_succeeded_event(command_name, database_name: db_name) end let(:key_vault_list_collections_event) do subscriber.started_events.find do |event| event.command_name == 'listCollections' && event.database_name == key_vault_db end end shared_examples 'it has a non-encrypted key_vault_client' do it 'does not register a listCollections event on the key vault client' do expect(key_vault_list_collections_event).to be_nil end end context 'when performing operations that need a document in the database' do before do result = encryption_client['users'].insert_one(ssn: ssn, age: 23) end describe '#aggregate' do let(:command_name) { 'aggregate' } before do encryption_client['users'].aggregate([{ '$match' => { 'ssn' => ssn } }]).first end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted expect( started_event.command["pipeline"].first["$match"]["ssn"]["$eq"] ).to be_ciphertext # Command succeeded event occurs before ssn is decrypted expect(succeeded_event.reply["cursor"]["firstBatch"].first["ssn"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#count' do let(:command_name) { 'count' } before do encryption_client['users'].count(ssn: ssn) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted # Command succeeded event does not contain any data to be decrypted expect(started_event.command["query"]["ssn"]["$eq"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#distinct' do let(:command_name) { 'distinct' } before do encryption_client['users'].distinct(:ssn) end it 'has encrypted data in command monitoring' do # Command started event does not contain any data to be encrypted # Command succeeded event occurs before ssn is decrypted expect(succeeded_event.reply["values"].first).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#delete_one' do let(:command_name) { 'delete' } before do encryption_client['users'].delete_one(ssn: ssn) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted # Command succeeded event does not contain any data to be decrypted expect(started_event.command["deletes"].first["q"]["ssn"]["$eq"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#delete_many' do let(:command_name) { 'delete' } before do encryption_client['users'].delete_many(ssn: ssn) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted # Command succeeded event does not contain any data to be decrypted expect(started_event.command["deletes"].first["q"]["ssn"]["$eq"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#find' do let(:command_name) { 'find' } before do encryption_client['users'].find(ssn: ssn).first end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted expect(started_event.command["filter"]["ssn"]["$eq"]).to be_ciphertext # Command succeeded event occurs before ssn is decrypted expect(succeeded_event.reply["cursor"]["firstBatch"].first["ssn"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#find_one_and_delete' do let(:command_name) { 'findAndModify' } before do encryption_client['users'].find_one_and_delete(ssn: ssn) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted expect(started_event.command["query"]["ssn"]["$eq"]).to be_ciphertext # Command succeeded event occurs before ssn is decrypted expect(succeeded_event.reply["value"]["ssn"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#find_one_and_replace' do let(:command_name) { 'findAndModify' } before do encryption_client['users'].find_one_and_replace( { ssn: ssn }, { ssn: '555-555-5555' } ) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted expect(started_event.command["query"]["ssn"]["$eq"]).to be_ciphertext expect(started_event.command["update"]["ssn"]).to be_ciphertext # Command succeeded event occurs before ssn is decrypted expect(succeeded_event.reply["value"]["ssn"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#find_one_and_update' do let(:command_name) { 'findAndModify' } before do encryption_client['users'].find_one_and_update( { ssn: ssn }, { ssn: '555-555-5555' } ) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted expect(started_event.command["query"]["ssn"]["$eq"]).to be_ciphertext expect(started_event.command["update"]["ssn"]).to be_ciphertext # Command succeeded event occurs before ssn is decrypted expect(succeeded_event.reply["value"]["ssn"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#replace_one' do let(:command_name) { 'update' } before do encryption_client['users'].replace_one( { ssn: ssn }, { ssn: '555-555-5555' } ) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted # Command succeeded event does not contain any data to be decrypted expect(started_event.command["updates"].first["q"]["ssn"]["$eq"]).to be_ciphertext expect(started_event.command["updates"].first["u"]["ssn"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#update_one' do let(:command_name) { 'update' } before do encryption_client['users'].replace_one({ ssn: ssn }, { ssn: '555-555-5555' }) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted # Command succeeded event does not contain any data to be decrypted expect(started_event.command["updates"].first["q"]["ssn"]["$eq"]).to be_ciphertext expect(started_event.command["updates"].first["u"]["ssn"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end describe '#update_many' do let(:command_name) { 'update' } before do # update_many does not support replacement-style updates encryption_client['users'].update_many({ ssn: ssn }, { "$inc" => { :age => 1 } }) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted # Command succeeded event does not contain any data to be decrypted expect(started_event.command["updates"].first["q"]["ssn"]["$eq"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end end describe '#insert_one' do let(:command_name) { 'insert' } before do encryption_client['users'].insert_one(ssn: ssn) end it 'has encrypted data in command monitoring' do # Command started event occurs after ssn is encrypted # Command succeeded event does not contain any data to be decrypted expect(started_event.command["documents"].first["ssn"]).to be_ciphertext end it_behaves_like 'it has a non-encrypted key_vault_client' end end
source 'https://rubygems.org' ruby '2.2.0' gem 'rails', '4.2.0' gem 'sass-rails', '~> 5.0' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.1.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' # Front-end framework gem 'foundation-rails' # Access to the MailChimp API gem 'gibbon' # Use Google Drive spreadsheets for data storage gem 'google_drive' # For Static pages gem 'high_voltage' # Forms made easy gem 'simple_form' group :development, :test do gem 'byebug' gem 'web-console', '~> 2.0' gem 'spring' gem 'sqlite3' end group :development do # Helps when things go wrong gem 'better_errors' # Supresses distracting messages in log gem 'quiet_assets' # Generates files for an application layout gem 'rails_layout' end group :production do gem 'pg' gem 'rails_12factor' gem 'thin' end group :test do gem 'minitest-spec-rails' gem 'minitest-rails-capybara' end
module ScorchedEarth class Player attr_reader :x, :y def initialize(x, y) @x = x @y = y freeze end end end
class PostsController < ApplicationController before_filter :authenticate_user! before_filter :load_community def create @post = @community.posts.new(post_params) @post.user = current_user @post.save end private def load_community @community = Community.find(params[:community_id]) end def post_params params.require(:post).permit(:text) end end
class Flight < Flight.superclass module Cell # A `<span>` that has a little pic of plane and says where the flight is from # and to. # # @!method self.call(model, opts = {}) # @param model [Flight] class Summary < Abroaders::Cell::Base property :id def show content_tag(:div, id: "flight_#{id}", class: 'flight') do "#{fa_icon('plane')} #{from} - #{to}" end end def self.airport_name_cell Destination::Cell::NameAndRegion end private def from name_and_region(model.from) end def name_and_region(dest) cell(self.class.airport_name_cell, dest) end def to name_and_region(model.to) end end end end