text
stringlengths
10
2.61M
class AddIndicesToSeasonDates < ActiveRecord::Migration[5.1] def change add_index :seasons, [:started_on, :ended_on] end end
class BasicRate # Daily cost in dollars attr_reader :daily # Weekly cost in dollars attr_reader :weekly # Monthly cost in dollars attr_reader :monthly def initialize(daily, weekly, monthly) @daily = daily @weekly = weekly @monthly = monthly end end
# # Cookbook Name:: hanlon # Recipe:: dnsmasq # # Copyright (C) 2014 # # # dhcp_interface = node['hanlon']['dhcp_interface'] no_dhcp_interface = node['hanlon']['no_dhcp_interface'] dhcp_interface_ip = node['network']['interfaces'][dhcp_interface]['addresses'].keys[1] dhcp_end_ip = node['hanlon']['dhcp_end_ip'] node.default['dnsmasq']['dns'] = { 'server' => "#{dhcp_interface_ip}@#{dhcp_interface}" } node.default['dnsmasq']['dhcp'] = { 'interface' => dhcp_interface, 'no-dhcp-interface' => no_dhcp_interface, 'domain' => 'hanlon.local', 'dhcp-match' => 'IPXEBOOT,175', 'dhcp-boot' => 'net:IPXEBOOT,bootstrap.ipxe', 'dhcp-boot' => 'undionly.kpxe', 'enable-tftp' => nil, 'tftp-root' => node['tftp']['directory'], 'dhcp-range' => "#{dhcp_interface},#{dhcp_interface_ip},#{dhcp_end_ip},12h", 'dhcp-option' => "option:ntp-server,#{dhcp_interface_ip}" } include_recipe 'dnsmasq'
class Error include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :status, :message validates_presence_of :status validates_presence_of :message def initialize(attributes = {}) attributes.each do |name, value| if name.eql?(:status) self.status = value elsif name.eql?(:message) self.message = value end end self.to_json end end
class MyType < ActiveHash::Base self.data = [ { id: 1, name: '--' }, { id: 2, name: 'とても内向的' }, { id: 3, name: '内向的' }, { id: 4, name: '内向的寄り' }, { id: 5, name: '両向的' }, { id: 6, name: '外向的寄り' }, { id: 7, name: '外向的' }, { id: 8, name: 'とても外向的' } ] include ActiveHash::Associations has_many :questions end
Sequel.migration do up do create_table(:artists) do primary_key :id String :name, :null => false DateTime :created_at, :null => false DateTime :updated_at, :null => false index :id, :unique => true end end down do drop_table(:artists) end end
Vagrant.configure("2") do |config| config.vm.box = "ubuntu/trusty64" config.vm.network :forwarded_port, guest: 9000, host: 9090 config.vm.network :forwarded_port, guest: 8000, host: 8080 config.vm.provision :shell, path: "vagrant.sh" end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. module Restore module Schedule class Base < ActiveRecord::Base set_table_name 'target_schedules' belongs_to :target, :class_name => 'Restore::Target::Base', :foreign_key => 'target_id' validates_presence_of :name validates_uniqueness_of :name, :scope => :target_id def after_save self.class.reload_schedules end def after_destroy self.class.reload_schedules end # this is a hack... maybe when backgroundrb gets more mature # we can unload a particular schedule and load it again def self.reload_schedules MiddleMan.unschedule_all find(:all).each do |s| s.schedule_worker end end def schedule_worker raise "abstract function!" end end end end
module FeatureHelpers # Submits the current form (clicking on input or button) def click_on_submit_button find('*[type=submit]').click end # Fills out login form def sign_in(user) fill_in 'user_email', with: user.email fill_in 'user_password', with: user.password click_on_submit_button end # Fills out all required fields in registration form def sign_up(user) fill_in 'user_email', with: user[:email] fill_in 'user_password', with: user[:password] fill_in 'user_password_confirmation', with: user[:password_confirmation] click_on_submit_button end end
class EssayAward < ActiveRecord::Base belongs_to :essay belongs_to :award before_validation :set_default_placement validates_presence_of :essay, :award def placement_string if placement.present? placement.ordinalize else nil end end def title if award.present? "#{award.title}: #{placement_string}" else "Award: #{placement_string}" end end private def set_default_placement self.placement ||= 1 end end
class CustomDeliveryStat < ActiveRecord::Base extend ScopeExtension::Stat extend ScopeExtension::Match belongs_to :custom after_create :set_default def set_default self.unsigned ||= 0 if self.has_attribute? :unsigned self.by_self ||= 0 if self.has_attribute? :by_self self.by_station ||= 0 if self.has_attribute? :by_station end end
require 'http' require 'oga' module ImageGetter class Scraper attr_reader :base_url, :document, :html def initialize(base_url,document) @base_url = base_url @document = document @html = Oga.parse_html(@document) end def links @links ||= get_links end def images @images ||= get_images end private def valid_href?(href) !!(href.is_a?(String) && href.length > 0 && !(/^#/ =~ href) && !(/^mailto:/ =~ href) ) end def get_links html.css('a[href]').inject([]) do |res, node| href = node.get('href') begin res << URI.join(base_url,href).to_s if valid_href?(href) rescue puts "UNABLE TO PARSE HREF: #{href.inspect} (from #{base_url})" end res end end def valid_image?(path) !!(path && /(jpg|gif|png)$/i =~ path) end def get_images res = [] grab = ->(selector,attribute) do html.css(selector).each do |node| path = node.get(attribute) res << URI.join(base_url,path).to_s if valid_image?(path) end end # These are roughly in the order they would appear in most pages grab.call 'meta[itemprop="image"]', 'content' grab.call 'meta[property="og:image"]', 'content' grab.call 'link[rel="image_src"]', 'href' grab.call 'img', 'src' res += css_images res end def css_images res = [] html.css('style').each do |node| node.text.scan(/url\((.*)\)/i).flatten.each do |path| path.tr!("'\"","") next unless valid_image?(path) begin res << URI.join(base_url,path).to_s rescue puts "UNABLE TO PARSE IMAGE PATH: #{path.inspect} (from #{base_url})" end end end res end class << self def call(url) res = HTTP.get(url) new(url,res.to_s) end end end end
class PrivilegeGroup < ApplicationRecord has_many :control_privileges end
def substrings(phrase, dictionary) substring_hash = Hash.new substring_hash.default = 0 phrase.downcase.gsub!(/[^a-z\s]/i, '') phrase = phrase.split(' ') phrase.each do |word| dictionary.each do |list| if word.include? list substring_hash[list] += 1 end end end substring_hash = Hash[ substring_hash.sort_by { |key, val| key } ] end
require 'date' require 'httparty' # references: # https://www.cryptocompare.com/api/#-api-data-price- module ApiHelper # currencies and coins we care about CORE_CURRENCIES = [{name: "US Dollar", symbol: "USD"}, {name: "Euro", symbol: "EUR"}, {name: "Japanese Yen", symbol: "JPY"}, {name: "British Pound", symbol: "GBP"}, {name: "Swiss Franc", symbol: "CHF"}, {name: "Canadian Dollar", symbol: "CAD"}, {name: "Australian Dollar", symbol: "AUD"}, {name: "New Zealand Dollar", symbol: "NZD"}, {name: "South African Rand", symbol: "ZAR"}, {name: "Chinese Yuan Renminbi", symbol: "CNY"}] CORE_COINS = [{name: "bitcoin", symbol: 'BTC'}, {name: "bitcoin-cash", symbol: "BCH"}, {name: "ethereum", symbol:"ETH"}, {name: "ethereum-classic",symbol:"ETC"}, {name: "litecoin", symbol:"LTC"}, {name: "dash", symbol:"DASH"}, {name: "monero", symbol:"XMR"}, {name: "zcash", symbol:"ZEC"}, {name: "ripple", symbol:"XRP"}] def getDateFromUnixDate(unixDate, format = '%H:%M %a %d %b %Y') # converts unixDate (String) and returns a friendly date (String) date = DateTime.strptime(unixDate, '%s') return date.strftime(format) end def coin_spot_price(fromSym = 'USD', *toSyms) # fromSym: symbol of coin or currency, as String # toSyms: to symbol, as multiple Strings # returns a hash / object literal, where each key (String) # returns a value that is equal to the number of fromSym per toSym # example, to get how much Bitcoin, Ethereum, Litecoin # we can buy with 1 USD: # result = coin_spot_price('USD', 'BTC', 'ETH', 'LTC') # p result["BTC"] # <-- how many BTC per dollar # to find out prices for 1 BTC in USD, JPY, CAD, CHF... # coin_spot_price("BTC", "USD", "CAD", "CHF", "JPY") # to get how many USD per BTC, use the prices method endpoint = "https://min-api.cryptocompare.com/data/price?" toSyms << "BTC" if toSyms.empty? url = endpoint + "fsym=" + fromSym.upcase + "&tsyms=" + toSyms.map{|coin| coin.upcase}.join(",") return HTTParty.get(url).parsed_response end def prices(base_currency, *coins) # returns a hash of prices in base_currency for each of the coins OR currency # for example, if we want to get prices of bitcoin, # ethereum, and litecoin in USD... # prices("USD", "BTC", "ETC", "LTC") if coins.empty? CORE_COINS.each do |coin| coins << coin[:symbol] end end hash_response = coin_spot_price(base_currency, coins.join(',')) result = {} hash_response.each do |coin, val| result[coin] = 1/val end result end def prices_all(base_currency) # use this to get back a list of coin prices, in base_currency # returns an array of hashes: # :symbol - returns the symbol of the coin or currency as a string, such as "BTC" # :name - name of the coin or currency (string) # example: # to get in USD, all coins in # CORE_COINS is a constant, an array of hashes result = CORE_COINS.clone # copy CORE_COINS, an array of hashes coins = result.map{|coin| coin[:symbol]} # array of strings, one for each coin response = prices(base_currency, *coins) # fetch prices, returned as a hash result.each do |coin| # update with prices coin[:price] = response[coin[:symbol]] if response.include? coin[:symbol] end return result end def price_hist(base_currency, num_days = 30, *coins) # example: get price history of bitcoin, ethereum, litecoin, # in USD, for last 100 days # price_hist("USD", 100, "BTC", "ETH", "LTC") # endpoint = 'https://min-api.cryptocompare.com/data/histoday' # url = endpoint + '?fsym=' + base_currency.upcase + '&tsym=' + coins.map{|coin| coin.upcase}.join(',') + '&limit=' + num_days.to_s # response = HTTParty.get(url).parsed_response # response end def price_hist_by_hour(from_currency="BTC", to_currency="USD", aggregate=1, num_hours=24*5) # from_currency = "BTC" # to_currency = "USD" # aggregate = 1 # hour frequency # num_hours = 24 * 5 # how many hours # url = 'https://min-api.cryptocompare.com/data/histohour?fsym=' + from_currency.upcase + '&tsym=' + to_currency.upcase + '&limit=' + num_hours.to_s + '&aggregate=' + aggregate.to_s # response = HTTParty.get(url).parsed_response # return response end end
class User < ActiveRecord::Base has_secure_password has_many :links validates :name, presence: { message: "is required. " } validates :email, presence: { message: "is required. " }, uniqueness: { message: "is already in use. " } validates :password, presence: { message: "is required. " }, confirmation: { message: "and confirmation don't match. " } validates :password_confirmation, presence: { message: "is required. " } end
class Team < ApplicationRecord has_many :course_users has_many :products belongs_to :course attr_accessor :studentsAmount, :leader, :leader_id, :logo_file, :access_requested def as_json options=nil options ||= {} options[:methods] = ((options[:methods] || []) + [:studentsAmount,:leader,:leader_id, :logo_file, :access_requested]) super options end end
require 'test_helper' class ShortUrlsControllerTest < ActionController::TestCase def login_user @user = User.create(name: "test_user", email: "test_user@example.com",password: "123456") session[:user_id] = @user.id end test "should autnenticate user" do get :index assert_redirected_to login_path end test 'logged in should get index' do login_user get :index assert_response :success assert_not_nil assigns(:short_urls) end test 'logged in should get new' do login_user get :new assert_response :success assert_not_nil assigns(:short_url) end end
# encoding: UTF-8 require 'test_helper' class OrderItemTest < ActiveSupport::TestCase setup do @client = Client.create name: "John", email: "john@gmail.com", password: 'tre543%$#', password_confirmation: 'tre543%$#' @order = @client.orders.create @product = Product.create name: 'Xaxá', price: 0.2 end test "validates presence of order" do oi = OrderItem.new order: nil assert ! oi.valid?, "item should be invalid" assert oi.errors[:order].any? end test "validates presence of product" do oi = OrderItem.new product: nil assert ! oi.valid?, "item should be invalid" assert oi.errors[:product].any? end test "validates presence of quantity" do oi = OrderItem.new quantity: nil assert ! oi.valid?, "item should be invalid" assert oi.errors[:quantity].any? end test "validates numericality of quantity" do oi = OrderItem.new quantity: "not a number" assert ! oi.valid?, "item should be invalid" assert oi.errors[:quantity].any? end test "set price and total" do oi = OrderItem.create! order: @order, product: @product, quantity: 10 assert_equal 0.2, oi.price assert_equal 2, oi.total end end
class Item < ApplicationRecord # refileに必要なメソッド attachment :item_image # アソシエーション belongs_to :user belongs_to :brand belongs_to :category # バリデーション validates :category_id, presence: true validates :price, presence: true end
class Admin::StudentsController < Admin::AdminController before_action :set_student, only: [:show, :edit, :update, :destroy] before_action :load_resources, only: [:new, :create, :edit, :update] # GET /students # GET /students.json def index @students = Student.all respond_with @students end # GET /students/new def new @student = Student.new respond_with @student end # GET /students/1/edit def edit end # POST /students # POST /students.json def create @student = Student.new(student_params) flash[:notice] = 'Student was successfully created.' if @student.save respond_with @student, :location => admin_students_path end # PATCH/PUT /students/1 # PATCH/PUT /students/1.json def update flash[:notice] = 'Student was successfully updated.' if @student.update(student_params) respond_with @student, :location => admin_students_path end # DELETE /students/1 # DELETE /students/1.json def destroy @student.destroy respond_with @student, :location => admin_students_path end private # Use callbacks to share common setup or constraints between actions. def set_student @student = Student.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student_params params.require(:student).permit(:name, :lattes, :adviser_id, :project_id, :avatar) end def load_resources @advisers = Adviser.all @projects = Project.all end end
class CoreLessonProblemType < ActiveRecord::Base belongs_to :lesson belongs_to :problem_type validates_presence_of :problem_type_id, :lesson_id validates_uniqueness_of :problem_type_id, :scope => :lesson_id end
class ArtyscisController < ApplicationController before_action :set_artysci, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] before_action :correct_user, only: [:edit, :update, :destroy] # GET /artyscis # GET /artyscis.json def index @artyscis = Artysci.all.order("nazwa ASC").paginate(:page => params[:page], :per_page => 15) end # GET /artyscis/1 # GET /artyscis/1.json def show @utwories = Utwory.where(:artysta => @artysci.nazwa) @gatunki = Utwory.select(:gatunek).where(:artysta => @artysci.nazwa).distinct end # GET /artyscis/new def new @artysci = current_user.artyscis.build end # GET /artyscis/1/edit def edit end # POST /artyscis # POST /artyscis.json def create @artysci = current_user.artyscis.build(artysci_params) respond_to do |format| if @artysci.save format.html { redirect_to @artysci, notice: 'Artysta został dodany.' } format.json { render :show, status: :created, location: @artysci } else format.html { render :new } format.json { render json: @artysci.errors, status: :unprocessable_entity } end end end # PATCH/PUT /artyscis/1 # PATCH/PUT /artyscis/1.json def update respond_to do |format| if @artysci.update(artysci_params) format.html { redirect_to @artysci, notice: 'Informacje o artyście zostały zaktualizowane.' } format.json { render :show, status: :ok, location: @artysci } else format.html { render :edit } format.json { render json: @artysci.errors, status: :unprocessable_entity } end end end # DELETE /artyscis/1 # DELETE /artyscis/1.json def destroy @artysci.destroy respond_to do |format| format.html { redirect_to artyscis_url, notice: 'Artysta został usunięty z bazy.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_artysci @artysci = Artysci.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def artysci_params params.require(:artysci).permit(:nazwa, :biografia, :kraj) end def correct_user @artysci = current_user.artyscis.find_by(id: params[:id]) redirect_to artyscis_path, notice: "Nie masz uprawnień do modyfikacji tego artysty" if @artysci.nil? end end
class Song attr_accessor :artist, :name def initialize(name) @name = name end def artist_name=(name) self.artist = Artist.find_or_create_by_name(name) artist.add_song(self) end def self.new_by_filename(file) song_info = file.chomp(".mp3").split(" - ") song = Song.new(song_info[1]) song.artist_name = song_info[0] song end end # class Song # attr_accessor :name, :artist # # @@all = [] # # def initialize(name, artist=nil) # @name = name # @artist = artist # @@all << self # end # # # def artist_name # if self.artist # self.artist.name # else # nil # end # end # # def self.new_by_filename # # row = file_name # # # # data = row.split(" - ") # # artist = data[0] # # song_name = data[1].gsub(".mp3", "") # # # # song = self.new # # song.name = song_name # # song.artist = artist # # song # # end # end
module Rounders module Matchers class CC < Rounders::Matchers::Matcher attr_reader :pattern def initialize(pattern) @pattern = pattern end def match(message) return if message.cc.nil? matches = message.cc.map do |address| address.match(pattern) end matches.compact end end end end
class RemoveForeignKeys < ActiveRecord::Migration[5.2] def change remove_foreign_key :order_items, :orders remove_foreign_key :order_items, :weddings end end
require_relative 'spec_helper' #get all the stuff we need for testing. require_relative '../scoring.rb' #include all the code in scoring.rb that we need to test. module Scrabble #Since all the tests in this spec correspond to Scoring, which lives inside Scrabble, can wrap the tests in the module also. describe Scoring do describe "#initialize" do it "should make a new instance of Scoring" do #this is testing that you can create a new instance of the Scoring class Scoring.new.must_be_instance_of(Scoring) end end describe "class" do it "should have a LETTER_SCORE length of 26" do #this just tests that the LETTER_SCORE data store has the correct length. Scoring::LETTER_SCORE.length.must_equal(26) end letters = ["A", "E", "I", "O", "U", "L", "N", "R", "S", "T"] letters.each do |letter| it "should have the correct LETTER_SCORE for a letter" do #Spot-check the constant LETTER_SCORE for correct letter score. Scoring::LETTER_SCORE[letter].must_equal 1 end end end describe "score" do it "should raise an error when a non-string is passed in" do #I want to check that if we pass something that isn't a string in, that it doesn't try to score it. #TODO: We could also add tests to make sure that the thing that is passed into the score method are single words (no spaces). proc {Scoring.score(1)}.must_raise(ArgumentError) end it "should strip punctuation when a non-alpha character is input" do Scoring.score("ETHOS!").must_equal(Scoring.score("ETHOS")) end it "should have a score method that takes in a word" do # From the requirements: self.score(word): returns the total score value for the given word. The word is input as a string (case insensitive). The chart in the baseline requirements shows the point value for a given letter. Scoring.score("cat") end it "score method should return the correct score" do # This test will input a specific word with a known score, assert equal that the score the method returns is the same. word = "CAT" Scoring.score(word).must_equal(5) end it "score method should add 50 points to a 7 letter word" do # From the requirements: A seven letter word means that a player used all the tiles. Seven letter words receive a 50 point bonus. word = "aarrghh" Scoring.score(word).must_equal(64) end it "score method should be case insensitive" do # self.score(word): returns the total score value for the given word. The word is input as a string (case insensitive). The chart in the baseline requirements shows the point value for a given letter. weird_word = "KiTTeN" word = "kitten" Scoring.score(weird_word).must_be_same_as(Scoring.score(word)) end it "score method should call strip_punctuation and strip it" do #The score method calls strip_punctuation and returns the word without any punctuation, so that if any punctuation is entered into the word, it scores it without the extra characters. Scoring.score("this!").must_be_same_as(Scoring.score("this")) end end describe "highest_score_from" do it "should have a highest_score_from method that takes in an array of words" do # From the requirements: self.highest_score_from(array_of_words): returns the word in the array with the highest score. # This tests that the method exists and takes in the right number of arguments. array_of_words = %w(CAT HAT GRAPE) Scoring.highest_score_from(array_of_words) end it "should have a highest_score_from method that takes in an array of words" do # From the requirements: self.highest_score_from(array_of_words): returns the word in the array with the highest score. # This tests that the correct word is returned. array_of_words = %w(CAT HAT GRAPE) Scoring.highest_score_from(array_of_words).must_equal("GRAPE") end it "highest_score_from should return the smaller of two words with the same score" do # From the requirements: It’s better to use fewer tiles, in the case of a tie, prefer the work with the fewest letters. # HATTER and MEOW are both 9 point words, but have different lengths. same_score = %w(HATTER MEOW CAT) Scoring.highest_score_from(same_score).must_equal("MEOW") end it "highest_score_from returns seven letter word even if there's shorter higher score word" do # From the requirements: There is a bonus for words that are seven letters. If the top score is tied between multiple words and one used all seven letters, choose the one with seven letters over the one with fewer tiles. #NOTE: the shorter word here is not real, but has the same score as the seven letter word (which includes the 50 point bonus). seven_vs = %w(QZQZZX aerated) Scoring.highest_score_from(seven_vs).must_equal("aerated") end it "highest score method returns first word if there's a tie in score/length" do # From the requirements: If the there are multiple words that are the same score and same length, pick the first one in the supplied list. # TOMCAT and KITTEN are both 6 letters long, and both have scores of 10. TOMCAT appears first, so that should be returned. same_length = %w(FOOT TOMCAT KITTEN) Scoring.highest_score_from(same_length).must_equal("TOMCAT") end end end end
class CreateUserProfiles < ActiveRecord::Migration def self.up create_table :user_profiles do |t| t.belongs_to :user t.integer :religion_id t.integer :sexual_orientation_id t.integer :country_id t.integer :gender_id t.integer :age_id t.integer :political_view_id t.string :language t.string :time_zone t.timestamps end add_index :user_profiles, :user_id add_index :user_profiles, [:religion_id, :sexual_orientation_id, :gender_id, :age_id, :political_view_id], :name => 'user_profiles_profile_match_index' end def self.down drop_table :user_profiles end end
# What will the following code print? Why? Don't run it until you've attempted to answer. def count_sheep 5.times do |sheep| puts sheep end end puts count_sheep # count_sheep prints the numbers 0 to 4 within the times method, and then returns 5, the initial integer times was called upon. puts count_sheep will then print 5
class RingGroupCallQuery < Types::BaseResolver description "Get the specified ring group call" argument :id, ID, required: true type Outputs::RingGroupCallType, null: false policy RingGroupPolicy, :view? def resolve RingGroupCall.find(input.id).tap { |call| authorize call.ring_group } end end
namespace :php do desc '配置 Laravel 環境。' task :setup do on roles(:app) do within release_path do execute :chmod, "u+x artisan" execute :chmod, "-R 777 storage/logs" execute :chmod, "-R 777 storage/framework" execute :chmod, "-R 777 bootstrap/cache" end end end desc '執行 Composer 更新。' after :setup, :composer do on roles(:app) do within release_path do execute :php, "composer update" end end end end
class ApplicationController < ActionController::Base INVALID_LOGIN_MESSAGE = 'Invalid email or password.' # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. # Could use with: null_session here and then wouldn't need to skip before filter in HealthpostController#facebook_page, but this feels more secure. protect_from_forgery with: :exception #The "signed_in" logic is necessary to avoid an endless redirection loop def redirect if user_signed_in? redirect_target = nil #Associate the Facebook page if a Facebook page association request comes in if current_user.provider_admin? && params[:tabs_added] current_user.provider.associate_fb_page(params[:tabs_added].keys.first) redirect_target = healthpost_path(current_user.provider_id) end #Redirect appropriately, with additional FB page permission checks if necessary and possible. redirect_target ||= if current_user.admin? users_path elsif came_from_facebook? if check_provider_id && ((current_user.provider_admin? && check_provider_admin) || current_user.regular_user?) healthpost_path(current_user.provider_id) else destroy_user_session_path end else current_user.provider_admin? ? providers_path : healthpost_path(current_user.provider_id) end #Destroy the cookies cookies.delete :page_id cookies.delete :page_admin #Put a message up if we denied entry - nice and vague flash[:alert] = INVALID_LOGIN_MESSAGE if redirect_target == destroy_user_session_path redirect_to redirect_target else redirect_to new_user_session_path end end private def came_from_facebook? (cookies[:page_id] && cookies[:page_admin]) end def check_provider_id cookies[:page_id] == current_user.provider.fb_page_id end def check_provider_admin cookies[:page_admin] == current_user.provider_admin?.to_s end end
class App < ActiveRecord::Base has_many :comments, dependent: :destroy, inverse_of: :app belongs_to :user, inverse_of: :apps validates :title, presence: true validates :description, presence: true validates :user_id, presence: true validates :app_photo, presence: true mount_uploader :app_photo, AppPhotoUploader end
# Defines our Vagrant environment # # -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| # create management node config.vm.define :management do |management_config| management_config.vm.box = "ubuntu/trusty64" management_config.vm.hostname = "management" management_config.vm.network :private_network, ip: "10.0.15.10" management_config.vm.provider "virtualbox" do |vb| vb.memory = "512" end management_config.vm.provision :shell, path: "scripts/bootstrap-management.sh" end # create load balancer config.vm.define :lb do |lb_config| lb_config.vm.box = "ubuntu/trusty64" lb_config.vm.hostname = "lb" lb_config.vm.network :private_network, ip: "10.0.15.11" lb_config.vm.network "forwarded_port", guest: 80, host: 8080 lb_config.vm.provider "virtualbox" do |vb| vb.memory = "256" end end # create some web servers # https://docs.vagrantup.com/v2/vagrantfile/tips.html (1..4).each do |i| config.vm.define "web#{i}" do |node| node.vm.box = "ubuntu/trusty64" node.vm.hostname = "web#{i}" node.vm.network :private_network, ip: "10.0.15.2#{i}" node.vm.provider "virtualbox" do |vb| vb.memory = "256" end end end end
FactoryGirl.define do factory :invite do email 'someone@there.org' token { InviteToken.new('secret').hashed } group_id 1 group_name 'users' role Role.group_admin trait :pending trait :accepted do accepted_at { Time.current } accepted_by 'socrates' end trait :revoked do revoked_at { Time.current } revoked_by 'socrates' end trait :expired do created_at { 1.year.ago } end end end
# frozen_string_literal: true require 'spec_helper' describe 'evergreen service' do it 'chooses the correct items amongst LBCC materials' do lbcc_available = EvergreenHoldings::Item.new({ status: 'Available', location: 'Stacks', owning_lib: 'LBCC Albany Campus Library' }) lbcc_childrens = EvergreenHoldings::Item.new({ status: 'Available', location: 'Children\'s Chapter Books', owning_lib: 'LBCC Albany Campus Library' }) lbcc_reserves = EvergreenHoldings::Item.new({ status: 'Available', location: 'Reserves', owning_lib: 'LBCC Benton Center' }) status = double connection = double status.stub(:copies) { [lbcc_reserves, lbcc_childrens, lbcc_available] } record_id = 1 Rails.cache.stub(:fetch).and_return(status) service = EvergreenService.new connection expected_items = [lbcc_available, lbcc_childrens] expect(expected_items).to include(service.best_item(record_id)) expect(service.best_items(record_id)).to match_array(expected_items) end it 'chooses LBCC reserves before a partner library holdings' do scio_available = EvergreenHoldings::Item.new({ status: 'Available', location: 'Stacks', owning_lib: 'Scio Public Library' }) lbcc_reserves = EvergreenHoldings::Item.new({ status: 'Available', location: 'Reserves', owning_lib: 'LBCC Benton Center' }) status = double connection = double status.stub(:copies) { [lbcc_reserves, scio_available] } record_id = 1 Rails.cache.stub(:fetch).and_return(status) service = EvergreenService.new connection expect(service.best_item(record_id)).to eq(lbcc_reserves) end it 'chooses partner libraries before unavailable LBCC' do scio_available = EvergreenHoldings::Item.new({ status: 'Available', location: 'Stacks', owning_lib: 'Scio Public Library' }) lbcc_unavailable = EvergreenHoldings::Item.new({ status: 'Checked out', location: 'Reserves', owning_lib: 'LBCC Benton Center' }) status = double connection = double status.stub(:copies) { [lbcc_unavailable, scio_available] } record_id = 1 Rails.cache.stub(:fetch).and_return(status) service = EvergreenService.new connection expect(service.best_item(record_id)).to eq(scio_available) end it 'chooses unavailable if nothing else exists' do scio_unavailable = EvergreenHoldings::Item.new({ status: 'Lost', location: 'Stacks', owning_lib: 'Scio Public Library' }) lbcc_unavailable = EvergreenHoldings::Item.new({ status: 'Checked out', location: 'Reserves', owning_lib: 'LBCC Benton Center' }) status = double connection = double status.stub(:copies) { [lbcc_unavailable, scio_unavailable] } record_id = 1 Rails.cache.stub(:fetch).and_return(status) service = EvergreenService.new connection expect(service.best_item(record_id)).to eq(lbcc_unavailable) end end
class ChoreReward < ActiveRecord::Base belongs_to :chore belongs_to :reward end
# frozen_string_literal: true require_relative '../validators/rating' # StringFilter is used for many-to-many # relation between Category and StringParameter class StringFilter < ApplicationRecord belongs_to :category belongs_to :string_parameter end
class TasksController < ApplicationController before_action :logged_in_user, only: [:new, :create, :index, :update, :show, :edit, :update, :destroy] before_action :correct_user, only: [:new, :create, :index, :update, :show, :edit, :update, :destroy] def new @task = Task.new end def create @task = Task.new(task_name: params[:task_name],content: params[:content],user_id: current_user.id) if @task.save flash[:success] = "タスクを新規作成しました。" redirect_to user_tasks_index_url else render :new end end def index @tasks = Task.where(user_id: current_user.id).all.order(id: "DESC") end def show @task = Task.find(params[:id]) @user = @task.user end def edit @task = Task.find(params[:id]) end def update @task = Task.find(params[:id]) @task.content = params[:content] @task.task_name = params[:task_name] if @task.save flash[:success] = "タスクを更新しました。" redirect_to user_tasks_index_url else render :edit end end def destroy @task = Task.find(params[:id]) @task.destroy flash[:success] = "タスクを削除しました。" redirect_to user_tasks_index_url end end
class AgentSessionsController < ApplicationController before_action :set_agent_session, only: [:show, :edit, :update, :destroy] # GET /agent_sessions # GET /agent_sessions.json def index if current_user.admin? @agent_sessions = AgentSession.all else @agent_sessions = AgentSession.joins('INNER JOIN agents ON agent_sessions.agent_id = agents.id INNER JOIN orgs ON agents.org_id = orgs.id').where('orgs.id = ?', current_user.org.id) end end # GET /agent_sessions/1 # GET /agent_sessions/1.json def show end # GET /agent_sessions/new def new @agent_session = AgentSession.new end # GET /agent_sessions/1/edit def edit end # POST /agent_sessions # POST /agent_sessions.json def create @agent_session = AgentSession.new(agent_session_params) respond_to do |format| if @agent_session.save format.html { redirect_to @agent_session, notice: 'Agent session was successfully created.' } format.json { render :show, status: :created, location: @agent_session } else format.html { render :new } format.json { render json: @agent_session.errors, status: :unprocessable_entity } end end end # PATCH/PUT /agent_sessions/1 # PATCH/PUT /agent_sessions/1.json def update respond_to do |format| if @agent_session.update(agent_session_params) format.html { redirect_to @agent_session, notice: 'Agent session was successfully updated.' } format.json { render :show, status: :ok, location: @agent_session } else format.html { render :edit } format.json { render json: @agent_session.errors, status: :unprocessable_entity } end end end # DELETE /agent_sessions/1 # DELETE /agent_sessions/1.json def destroy @agent_session.destroy respond_to do |format| format.html { redirect_to agent_sessions_url, notice: 'Agent session was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_agent_session @agent_session = AgentSession.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def agent_session_params params.require(:agent_session).permit(:agent_id, :start_time, :end_time, :hostname, :ros_master_uri, :session_status, :token) end end
require 'rails_helper' describe 'A visitor' do context 'visits stations index' do it 'sees all stations with name, dock count, city, installation date' do station_1 = Station.create(name: 'City hall', dock_count: 20, city: 'San Jose', installation_date: Time.now, created_at: 2018-02-21, updated_at: 2018-03-21) station_2 = Station.create(name: 'South Blvd', dock_count: 15, city: 'San Jose', installation_date: Time.now, created_at: 2018-01-11, updated_at: 2018-02-11) visit stations_path expect(page).to have_content(station_1.name) expect(page).to have_content(station_1.dock_count) expect(page).to have_content(station_1.city) expect(page).to have_content(station_1.installation_date.strftime('%b %d %Y')) expect(page).to have_content(station_2.name) expect(page).to have_content(station_2.dock_count) expect(page).to have_content(station_2.city) expect(page).to have_content(station_2.installation_date.strftime('%b %d %Y')) expect(page).to_not have_button('Edit') expect(page).to_not have_button('Delete') end it 'can click on a station name to go to that station show page' do station_1 = Station.create(name: 'City hall', dock_count: 20, city: 'San Jose', installation_date: Time.now, created_at: 2018-02-21, updated_at: 2018-03-21) visit stations_path click_link "#{station_1.name}" expect(current_path).to eq(station_path(station_1)) end end end
#!/usr/bin/env ruby # # Shortcut for git commit -am && push # # Automatically prefixed commit message with ticket number # puts `git status` commit_message = ARGV.join(" ").strip full_git_branch_path = `git symbolic-ref HEAD`.chomp git_branch_name = full_git_branch_path.split('/').last commit_prefix = git_branch_name.match(/([A-Z]{1,})-[0-9]{1,}/)[0] puts "Branch name : #{git_branch_name}" puts "Commit prefix : #{commit_prefix}" if commit_message == "" print "Commit message : " commit_message = gets.chomp end if commit_message != "" puts `git commit -am \"#{commit_prefix} #{commit_message}\" && git push` else puts "Commit message required" end
# frozen_string_literal: true require 'spec_helper' describe Apartment do describe '#config' do let(:excluded_models) { ['Company'] } let(:seed_data_file_path) { Rails.root.join('db/seeds/import.rb') } def tenant_names_from_array(names) names.each_with_object({}) do |tenant, hash| hash[tenant] = Apartment.connection_config end.with_indifferent_access end it 'yields the Apartment object' do described_class.configure do |config| config.excluded_models = [] expect(config).to eq(described_class) end end it 'sets excluded models' do described_class.configure do |config| config.excluded_models = excluded_models end expect(described_class.excluded_models).to eq(excluded_models) end it 'sets use_schemas' do described_class.configure do |config| config.excluded_models = [] config.use_schemas = false end expect(described_class.use_schemas).to be false end it 'sets seed_data_file' do described_class.configure do |config| config.seed_data_file = seed_data_file_path end expect(described_class.seed_data_file).to eq(seed_data_file_path) end it 'sets seed_after_create' do described_class.configure do |config| config.excluded_models = [] config.seed_after_create = true end expect(described_class.seed_after_create).to be true end it 'sets tenant_presence_check' do described_class.configure do |config| config.tenant_presence_check = true end expect(described_class.tenant_presence_check).to be true end it 'sets active_record_log' do described_class.configure do |config| config.active_record_log = true end expect(described_class.active_record_log).to be true end context 'when databases' do let(:users_conf_hash) { { port: 5444 } } before do described_class.configure do |config| config.tenant_names = tenant_names end end context 'when tenant_names as string array' do let(:tenant_names) { %w[users companies] } it 'returns object if it doesnt respond_to call' do expect(described_class.tenant_names).to eq(tenant_names_from_array(tenant_names).keys) end it 'sets tenants_with_config' do expect(described_class.tenants_with_config).to eq(tenant_names_from_array(tenant_names)) end end context 'when tenant_names as proc returning an array' do let(:tenant_names) { -> { %w[users companies] } } it 'returns object if it doesnt respond_to call' do expect(described_class.tenant_names).to eq(tenant_names_from_array(tenant_names.call).keys) end it 'sets tenants_with_config' do expect(described_class.tenants_with_config).to eq(tenant_names_from_array(tenant_names.call)) end end context 'when tenant_names as Hash' do let(:tenant_names) { { users: users_conf_hash }.with_indifferent_access } it 'returns object if it doesnt respond_to call' do expect(described_class.tenant_names).to eq(tenant_names.keys) end it 'sets tenants_with_config' do expect(described_class.tenants_with_config).to eq(tenant_names) end end context 'when tenant_names as proc returning a Hash' do let(:tenant_names) { -> { { users: users_conf_hash }.with_indifferent_access } } it 'returns object if it doesnt respond_to call' do expect(described_class.tenant_names).to eq(tenant_names.call.keys) end it 'sets tenants_with_config' do expect(described_class.tenants_with_config).to eq(tenant_names.call) end end end end end
module Constantizable include ActiveSupport::Concern def get_constantized(type) self.class.get_constantized(type) end module ClassMethods def get_constantized(type) elements = constants.map {|sym| sym.to_s.underscore } elements.include?(type) ? get_constant(type) : raise_invalid_type end def get_constant(type) "#{name}::#{type.camelcase}".constantize end def raise_invalid_type available = constants.map { |sym_class| sym_class.to_s.underscore }.join(", ") raise Exceptions::Simple.build(message: "is invalid, available: #{available}", field: :type) end end end
""" Hand Score Write a method hand_score that takes in a string representing a hand of cards and returns it's total score. You can assume the letters in the string are only A, K, Q, J. A is worth 4 points, K is 3 points, Q is 2 points, and J is 1 point. The letters of the input string not necessarily uppercase. """ def hand_score(hand) total = 0 points = { "A" => 4, "K" => 3, "Q" => 2, "J" => 1 } hand.each_char do |char| total += points[char.upcase] end return total end puts hand_score("AQAJ") #=> 11 puts hand_score("jJka") #=> 9
require_relative('../db/sql_runner') require_relative('../models/ticket') class Customer attr_accessor :name, :funds attr_reader :id def initialize(options) @id = options['id'].to_i if options['id'] @name = options['name'] @funds = options['funds'] end # CRUD # create def save() # sql sql = "INSERT INTO customers (name, funds) VALUES ($1, $2) RETURNING id;" # values values = [@name, @funds] # sql runner results = SqlRunner.run(sql, "save_customer", values) # set id @id = results[0]['id'].to_i end # read def self.all() # sql sql = "SELECT * FROM customers;" # values values = [] # sql runner results = SqlRunner.run(sql, "get_all_customers", values) # return return results.map {|customer| Customer.new(customer)} end # update def update() # sql sql = "UPDATE customers SET (name, funds) = ($1, $2) WHERE id = $3;" # values values = [@name, @funds, @id] # sql runner SqlRunner.run(sql, "update_customer", values) end # delete def self.delete_all() # sql sql = "DELETE FROM customers;" # values values = [] # sql runner SqlRunner.run(sql, "delete_all_customers", values) end def delete() # sql sql = "DELETE FROM customers WHERE id = $1;" # values values = [@id] # sql runner SqlRunner.run(sql, "delete_customer", values) end # show all customer's tickets def booked_films() # sql sql = "SELECT films.* FROM films INNER JOIN tickets ON films.id = tickets.film_id WHERE customer_id = $1;" # values values = [@id] # sql runner results = SqlRunner.run(sql, "get_all_booked_films", values) # return return results.map {|film| Film.new(film)} end # count customer tickets def number_tickets() booked_films().count() # alternative sql: # # sql # sql = "SELECT COUNT(films.id) FROM films INNER JOIN tickets ON films.id = tickets.film_id WHERE customer_id = $1;" # # values # values = [@id] # # results # results = SqlRunner.run(sql, "get_number_tickets", values) # # return # return results[0]['count'].to_i end # buy ticket def buy_ticket(film) @funds -= film.price() update() ticket = Ticket.new( { 'customer_id' => @id, 'film_id' => film.id } ) ticket.save() end end
json.array!(@posts) do |post| json.label post.title json.id post.id end
require 'spec_helper' describe Metasploit::Model::Visitation::Visitor do context 'validations' do it { should validate_presence_of :block } it { should validate_presence_of :module_name } it { should validate_presence_of :parent } end context '#initialize' do subject(:instance) do described_class.new( :module_name => module_name, :parent => parent, &block ) end let(:block) do lambda { |node| node } end let(:module_name) do 'Visited::Node' end let(:parent) do Class.new end it 'should set #block from &block' do instance.block.should == block end it 'should set #module_name from :module_name' do instance.module_name.should == module_name end it 'should set #parent from :parent' do instance.parent.should == parent end end end
#!/bin/env ruby # encoding: utf-8 $nataniev.require("action","tweet") class VesselDictionarism include Vessel def initialize id = 0 super @name = "Dictionarism" @docs = "A twitter bot that makes -isms out of words. A fork of an old [Nataniev automaton](https://wiki.xxiivv.com/#dictionarism)" @path = File.expand_path(File.join(File.dirname(__FILE__), "/")) install(:default, :generate) install(:generic, :document) install(:generic, :tweet) end end class ActionGenerate include Action def initialize q = nil super @name = "Generate" @docs = "Generate a new -ism" end def act q = nil timeDiff = Time.new.to_i - Date.new(2015,8,21).to_time.to_i daysGone = (timeDiff/86400) chapter = (daysGone * 24) + Time.now.hour word_type = "" dict = {} Memory_Array.new("dictionary").to_a.each do |line| word_type = line['C'] if !dict[word_type] then dict[word_type] = [] end dict[word_type].push(line['WORD']) end word = q.to_s != "" ? q : dict["N"][chapter % dict["N"].length] # -te if word[-2,2] == "te" word = word[0...-1]+"ism" # -ve elsif word[-2,2] == "ve" word = word[0...-1]+"ism" # -ly elsif word[-2,2] == "ly" word = word+"ism" # -ed elsif word[-2,2] == "ed" word = word[0...-2]+"ism" # -ist elsif word[-3,3] == "ist" word = word[0...-3]+"ism" # -y elsif word[-1,1] == "y" word = word[0...-1]+"ism" else word += "ism" end return word.capitalize end end class ActionTweet def account return "dictionarism" end def payload return ActionGenerate.new(@host).act end end
class Tag < ActiveRecord::Base has_many :taggings, dependent: :destroy has_many :events, through: :taggings end
require './lib/world' describe World do before do @world = World.new end it 'set cell alive should set the cell to live' do @world.set_alive(1,1) expect(@world.is_alive?(1,1)).to be true end it 'set cell alive, other cells should be dead' do @world.set_alive(1,1) expect(@world.is_alive?(2,1)).to be false end context 'a live cell with neighbours' do it '0 neighbours count should be 0' do expect(@world.neighbours_count(5,6)).to eq(0) end it 'should not count itself' do @world.set_alive(6,6) expect(@world.neighbours_count(6,6)).to eq(0) end it '1 neighbours count should be 1' do @world.set_alive(6,6) expect(@world.neighbours_count(5,6)).to eq(1) end it '2 neighbours count should be 2' do @world.set_alive(6,6) @world.set_alive(6,5) expect(@world.neighbours_count(5,6)).to eq(2) end it '3 neighbours count should be 2' do @world.set_alive(6,6) @world.set_alive(6,5) @world.set_alive(6,7) expect(@world.neighbours_count(5,6)).to eq(3) end end context 'game rules' do it 'Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.' do @world.set_alive(6,6) @world.set_alive(6,5) @world.tick expect(@world.is_alive?(6,5)).to be false end it 'Any live cell with more than three live neighbours dies, as if by overcrowding.' do @world.set_alive(6,6) @world.set_alive(6,5) @world.set_alive(6,4) @world.set_alive(5,5) @world.set_alive(7,5) @world.tick expect(@world.is_alive?(6,5)).to be false end it ' Any live cell with two live neighbours lives on to the next generation.' do @world.set_alive(6,6) @world.set_alive(6,5) @world.set_alive(6,4) @world.tick expect(@world.is_alive?(6,5)).to be true end it ' Any live cell with three live neighbours lives on to the next generation.' do @world.set_alive(6,6) @world.set_alive(6,5) @world.set_alive(6,4) @world.set_alive(7,5) @world.tick expect(@world.is_alive?(6,5)).to be true end it 'Any dead cell with exactly three live neighbours becomes a live cell.' do end end end
require 'rspec' require 'task' require 'list' describe Task do it 'is initialized with a description' do test_task = Task.new('scrub the zebra') test_task.should be_an_instance_of Task end it 'lets you read the description out' do test_task = Task.new('scrub the zebra') test_task.description.should eq 'scrub the zebra' end end describe List do it 'is initialized with a description' do test_list = List.new('home') test_list.should be_an_instance_of List end it 'lets you read the description out' do test_list = List.new('home') test_list.description.should eq 'home' end it 'takes tasks for each list' do test_list = List.new('home') test_list.add_task('new').should eq ['new'] end end
Snackstack::Application.routes.draw do resources :items devise_for :users root to: "home#index" end
require 'rails_helper' RSpec.describe BooksController, type: :controller do let(:test_book){ Book.create title: "Test Book", author: "Author Name", isbn: 1234, pub_date: 2008, genre: "fiction", format: "pb", publisher: "Test Pub", summary: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor, asperiores neque porro." } describe "GET #index" do it "returns http success" do get :index expect(response).to have_http_status(:success) end end describe 'GET #new' do it "assigns a new book to @book variable" do get :new book = test_book expect(book).to be_an_instance_of Book end end end
class Spree::Calculator::PrinceEdwardTax < Spree::Calculator def self.description "Prince Edward Tax" end def self.register super end def compute(order) calculate_taxation(order.item_total) end private def calculate_taxation(total) gst = total * 0.05 pst = (total + gst) * 0.1 #PST tax = round_to_two_places(gst + pst) return tax end def round_to_two_places(amount) BigDecimal.new(amount.to_s).round(2, BigDecimal::ROUND_HALF_UP) end end
# frozen_string_literal: true require 'integration_test' class SurveyRequestsControllerTest < IntegrationTest setup do @survey_request = survey_requests(:sent) login(:uwe) end test 'should get index' do get survey_requests_path assert_response :success end test 'should get new' do get new_survey_request_url assert_response :success end test 'should create survey_request' do assert_difference('SurveyRequest.count') do post survey_requests_url, params: { survey_request: { completed_at: @survey_request.completed_at, member_id: members(:sebastian).id, survey_id: @survey_request.survey_id, } } end assert_redirected_to SurveyRequest.last end test 'should show survey_request' do get survey_request_url(@survey_request) assert_response :success end test 'should get edit' do get edit_survey_request_url(@survey_request) assert_response :success end test 'should update survey_request' do patch survey_request_url(@survey_request), params: { survey_request: { completed_at: @survey_request.completed_at, member_id: @survey_request.member_id, survey_id: @survey_request.survey_id, } } assert_redirected_to survey_request_url(@survey_request) end test 'should destroy survey_request' do assert_difference('SurveyRequest.count', -1) do delete survey_request_url(@survey_request) end assert_redirected_to survey_requests_path end def test_answer_form get "/svar/#{survey_requests(:sent).id}" assert_response :success assert_match(/val\(\) && /, response.body) end def test_save_answers post "/svar/#{id(:sent)}", params: { survey_request: { survey_answers_attributes: { '0': { survey_question_id: id(:first_question), answer: "Familie\r\n" }, '1': { survey_question_id: id(:second_question), answer: ['', "Bekjent\r\n", 'www.jujutsu.no'] }, '2': { survey_question_id: id(:summary_question), answer_free: '' }, }, }, } assert_redirected_to action: :thanks follow_redirect! assert_select 'h2', 'Tusen takk!' end end
class Payment < ActiveRecord::Base validates_uniqueness_of :number belongs_to :customer_company, :class_name => 'CustomerCompany' belongs_to :bank belongs_to :salesman, :class_name => 'Account' belongs_to :account belongs_to :order before_create do self.number = 'ZF-' + Time.now.strftime("%Y%m%d") + SecureRandom.hex(7).upcase end after_create do if self.order_id? and self.total? temp_order = self.order paied = temp_order.paied + self.total unpaied = temp_order.due - paied - temp_order.sales_return_total temp_order.update(paied: paied, unpaied: unpaied) end end end
# Exceptions and Stack Traces =begin For the purposes of this section an exception can be viewed as synonymous with an error. During the course of program execution, many things can go wrong for a variety of reasons, and when something does go wrong, usually we say "an exception is raised". This is a common technical phrase that just means your code encountered some sort of error condition. When an exception is raised, it is usually accompanied by a large output of text of what looks like gibberish. It's in this gibberish that you'll find the clues to the source of the problem, and it's important to start developing an eye for scanning and parsing this gibberish output. This skill will end up being one of the most important things to develop over time, because if you're like most programmers, your code will generate a lot of exceptions. =end # Common Built-In Error Types that include a a message =begin StandardError TypeError ArgumentError NoMethodError RuntimeError SystemCallError ZeroDivisionError RegexpError IOError EOFError ThreadError ScriptError SyntaxError LoadError NotImplementedError SecurityError =end
require File.dirname(__FILE__) + '/../../../spec_helper' require 'stringio' require 'zlib' describe 'Zlib::GzipFile#finish' do before(:each) do @io = StringIO.new @gzip_writer = Zlib::GzipWriter.new @io end after :each do @gzip_writer.close unless @gzip_writer.closed? end it 'closes the GzipFile' do @gzip_writer.finish @gzip_writer.closed?.should be_true end it 'does not close the IO object' do @gzip_writer.finish @io.closed?.should be_false end it 'returns the associated IO object' do @gzip_writer.finish.should eql(@io) end it 'raises Zlib::GzipFile::Error if called multiple times' do @gzip_writer.finish lambda { @gzip_writer.finish }.should raise_error(Zlib::GzipFile::Error) end end
require 'rails_helper' describe Machine, type: :model do describe 'relationships' do it { is_expected.to belong_to(:owner) } it { is_expected.to have_many(:snacks) } end describe 'validations' do it { is_expected.to validate_presence_of(:location) } end describe 'methods' do before(:all) do DatabaseCleaner.clean end after(:all) do DatabaseCleaner.clean end it 'can calculate average price' do owner = Owner.create!(name: "Sam's Snacks") dons = owner.machines.create!(location: "Don's Mixed Drinks") snacks = [ dons.snacks.create!(name: 'Yummy Gummies', price: 200), dons.snacks.create!(name: 'Yucky Uckys', price: 50), dons.snacks.create!(name: 'Hey, not bad.', price: 300), dons.snacks.create!(name: 'Sub par at best.', price: 50) ] avg = snacks.reduce(0) { |s, snack| s + snack.price } avg /= snacks.length.to_f avg /= 100.0 expect(dons.average_price).to be(avg) end end end
class Players attr_accessor :name, :score def initialize(name) @name = name @score = 3 end def decrement_score @score -= 1 end def player_live? @score > 0 end end
class AddCnPropertyExplanationField < ActiveRecord::Migration RAILS_ENV="chinese" def self.up config = ActiveRecord::Base.configurations["chinese"] ActiveRecord::Base.establish_connection(config) add_column :cn_properties, :explanation, :string end def self.down config = ActiveRecord::Base.configurations["chinese"] ActiveRecord::Base.establish_connection(config) remove_column :cn_properties, :explanation end end
Pod::Spec.new do |s| # Root specification s.name = "box-ios-browse-sdk" s.version = "1.0.4" s.summary = "iOS Browse SDK." s.homepage = "https://github.com/box/box-ios-browse-sdk" s.license = { :type => "Apache License, Version 2.0", :file => "LICENSE" } s.author = "Box" s.source = { :git => "https://github.com/box/box-ios-browse-sdk.git", :tag => "v#{s.version}" } # Platform s.ios.deployment_target = "7.0" # File patterns s.ios.source_files = "BoxBrowseSDK/BoxBrowseSDK/*.{h,m}", "BoxBrowseSDK/BoxBrowseSDK/**/*.{h,m}" s.ios.public_header_files = "BoxBrowseSDK/BoxBrowseSDK/*.h", "BoxBrowseSDK/BoxBrowseSDK/**/*.h" s.resource_bundle = { 'BoxBrowseSDKResources' => [ 'BoxBrowseSDK/BoxBrowseSDKResources/Assets/*.*', 'BoxBrowseSDK/BoxBrowseSDKResources/Icons/*.*', ] } # Build settings s.requires_arc = true s.ios.header_dir = "BoxBrowseSDK" s.module_name = "BoxBrowseSDK" s.dependency "box-ios-sdk" s.dependency 'MBProgressHUD', '~> 0.9.1' end
class MigrateSourceDatabasesToReferences < ActiveRecord::Migration[6.1] # This IRREVERSIBLE migration transforms data from the deprecated # source_databases table into references associated with the respective # records. # # It also creates paper_trail 'create' versions for records previously # imported directly into the database, noting the original source database. # Unfortunately since only c14s had a source_database column, we can only do # this unambiguously for c14s. # # See https://github.com/xronos-ch/xronos.rails/issues/136 for rationale. def change # Make references from source_databases # - First ensuring pkey sequence is in sync # - Saving a temporary relation between source_databases and references (in both tables) # - Wrapping citation in dummy BibTeX so as to not break views execute %(ALTER TABLE "references" ADD COLUMN source_database_id INT;) execute %(SELECT setval('public.references_id_seq', (SELECT MAX(id) FROM "references")+1);) execute %( INSERT INTO "references" (short_ref, bibtex, created_at, updated_at, source_database_id) SELECT name AS short_ref, '@Misc{' || name || ', url = {' || url || '}, note = {' || citation || '} }' AS bibtex, created_at, updated_at, id AS source_database_id FROM source_databases; ) execute %(ALTER TABLE source_databases ADD COLUMN reference_id INT;) execute %( UPDATE source_databases SET reference_id = ref.id FROM "references" AS ref WHERE source_databases.id = ref.source_database_id ) # Create citations to references for c14s execute %( INSERT INTO citations (reference_id, citing_type, citing_id) SELECT source_databases.reference_id AS reference_id, 'C14' AS citing_type, c14s.id AS citing_id FROM c14s, source_databases WHERE source_databases.id = c14s.source_database_id; ) # Create versions (event: create) for the initial import # - for models that has_paper_trail (c14s, c14_labs, typos, samples, materials, taxons, contexts, sites, site_types, references) # - With the same created_date as the record # - Linking to the import script (https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R) # # For c14s: # - Noting the name of the source database # - Linking to the source database and c14bazAAR execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'C14' AS item_type, c14s.id AS item_id, 'create' AS event, 3 AS whodunnit, c14s.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from [', source_databases.name, '](', source_databases.url, ') via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM c14s, source_databases WHERE c14s.source_database_id = source_databases.id; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'C14Lab' AS item_type, c14_labs.id AS item_id, 'create' AS event, 3 AS whodunnit, c14_labs.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM c14_labs; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'Typo' AS item_type, typos.id AS item_id, 'create' AS event, 3 AS whodunnit, typos.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM typos; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'Sample' AS item_type, sAMPLES.ID as ITEM_ID, 'create' AS event, 3 AS whodunnit, samples.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM samples; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'Material' AS item_type, materials.id AS item_id, 'create' AS event, 3 AS whodunnit, materials.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM materials; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'Taxon' AS item_type, taxons.id AS item_id, 'create' AS event, 3 AS whodunnit, taxons.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM taxons; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'Context' AS item_type, contexts.id AS item_id, 'create' AS event, 3 AS whodunnit, contexts.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM contexts; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'Context' AS item_type, contexts.id AS item_id, 'create' AS event, 3 AS whodunnit, contexts.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM contexts; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'Site' AS item_type, sites.id AS item_id, 'create' AS event, 3 AS whodunnit, sites.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM sites; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'SiteType' AS item_type, site_types.id AS item_id, 'create' AS event, 3 AS whodunnit, site_types.created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM site_types; ) execute %( INSERT INTO versions (item_type, item_id, event, whodunnit, created_at, whodunnit_user_email, revision_comment) SELECT 'Reference' AS item_type, "references".id AS item_id, 'create' AS event, 3 AS whodunnit, "references".created_at AS created_at, 'admin@xronos.ch' AS whodunnit_user_email, CONCAT('Imported from source database via [c14bazAAR](https://github.com/xronos-ch/xronos-import/blob/eba0da90659b60fdcd698adc3e40e904e03e5a29/scripts/xronos_import_20220202.R)') AS revision_comment FROM "references"; ) # Drop temporary foreign key from references execute %( ALTER TABLE "references" DROP COLUMN source_database_id ) # Drop source_database foreign keys remove_column :c14s, :source_database_id # Drop source_databases drop_table :source_databases end end
# == Schema Information # # Table name: path_subscriptions # # id :integer not null, primary key # path_id :integer # user_id :integer # # Indexes # # index_path_subscriptions_on_path_id (path_id) # index_path_subscriptions_on_user_id (user_id) # FactoryGirl.define do factory :path_subscription do user { create(:user) } path { create(:path) } end end
# frozen_string_literal: true # # Copyright (c) 2019-present, Blue Marble Payroll, LLC # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # require 'spec_helper' describe Proforma::HtmlRenderer::Writer do let(:intro_name) { 'example.txt.erb' } let(:aloha_name) { 'aloha.txt.erb' } let(:intro_template) { 'My name is <%= first_name %>' } subject do described_class.new( directory: File.join(__dir__, '..', '..', 'fixtures'), files: { intro_name => intro_template } ) end describe '#initialize with no arguments' do it 'should set directory to this libraries template dir' do actual = File.expand_path(described_class.new.send(:directory)) expected = File.expand_path(File.join(__dir__, '..', '..', '..', 'templates')) expect(actual).to eq(expected) end end context 'when using cached files' do it 'renders ERB template' do expected = 'My name is Earl' expect(subject.render(intro_name, first_name: 'Earl')).to eq(expected) end end context 'when not using cached files' do it 'renders ERB template' do expected = 'Aloha, Matty Cakes!' expect(subject.render(aloha_name, full_name: 'Matty Cakes')).to eq(expected) end end end
require 'spec_helper' describe Nature::Service do include FakeFS::SpecHelpers before(:each) do # Bug in FakeFS, we dont need to worry about it here File.stub(:chmod) end describe ".new" do it "sets up the class propery" do path = Pathname.new('/etc/sv/test-service') cwd = Pathname.new('/apps/fake_app') command = "cat foo" environment = Hash["FOO" => 'bar', "BAZ" => 'bat'] result = Nature::Service.new(path, :command => command, :cwd => cwd, :environment => environment) result.cwd.should == '/apps/fake_app' result.environment.should == environment result.command.should == command result.path.should == '/etc/sv/test-service' result.active_path.should == '/service' result.run_script_path.should == '/etc/sv/test-service/run' result.log_script_path.should == '/etc/sv/test-service/log/run' result.log_dir.should == '/var/log/test-service' end end it "creates the necessary files and folders" do service = Nature::Service.new(Pathname.new('/etc/sv/test-service'), :command => 'ls -lah', :cwd => Pathname.new('/tmp/app'), :environment => {}) service.create! File.exists?(service.run_script_path).should be_true File.exists?(service.log_script_path).should be_true File.directory?(service.log_dir).should be_true end it "can symlink the service to make it active" do FileUtils.should_receive(:ln_sf).with('/etc/sv/test-service', '/service') Nature::Service.new(Pathname.new('/etc/sv/test-service'), :command => 'ls -lah', :cwd => Pathname.new('/tmp/app'), :environment => {}).activate! end end
require 'thor' require 'fileutils' class Testing < Thor @@path = File.dirname(__FILE__) @@templates_path = @@path + '/templates' @@framework_templates_path = @@path + '/frameworks_templates' desc 'new <project_name>', 'Create new empty project' method_option :with_rspec, default: false, required: false, desc: "Create necessary files for rspec", aliases: "-trs", type: :boolean def new(name) create_file("#{name}/first_file.rb", read_from_file("#{templates_path}/template#1.rb")) create_file("#{name}/folder/second_file.feature", read_from_file("#{templates_path}/template#2.feature")) if options[:with_rspec] create_file("#{name}/rspec/example_spec.rb", read_from_file("#{templates_path}/template#2.rb")) end puts("-- Project with name #{name} has been created --") end desc 'create_test_for <feature_path> <destination_folder>', 'Create test suite for given feature' def create_test_for(feature_path, destination_folder) step_strings = get_step_strings(feature_path) file_content = file_header_template file_content.concat(step_strings.map{ |name| write_step(name) }.join("\n")) if step_strings.any? file_content.concat("end\n") full_file_path = "#{destination_folder}/#{feature_path.match(/\/(\w+)(.\w+)?$/)[1]}.rb" create_file(full_file_path, file_content) puts "-- Test has been created --" end desc 'create_config <path>', 'Allow to create config according to your needs' method_option :framework, required: true, desc: "You need to choose which", type: :string, liases: "-fr" def create_config(path) file_content = nil file_name = 'config' if options["framework"] == "phoenix" file_content = read_from_file("#{framework_templates_path}/ph_template.exs") file_name.concat('.exs') elsif options["framework"] == "rails" file_content = read_from_file("#{framework_templates_path}/ror_template.rb") file_name.concat('.rb') else puts "Template for framework=#{options["framework"]} does not exist" end if file_content create_file("#{path}/#{file_name}", file_content) end end private def file_header_template [ "require 'spec_helper'\n", "module CrudForNewReasonSteps\n" ].join("\n") end def write_step(name) [ " step '#{name.strip}' do", " # implement step here", " end\n" ].join("\n") end def get_step_strings(feature_name) file_text = File.open(feature_name).read file_text = file_text.gsub(/\n\r?/, "\n") steps = [] file_text.each_line do |line| if line.match(/\s*(Допустим|Когда|Тогда).+/) steps << line end end steps end def templates_path @@templates_path end def framework_templates_path @@framework_templates_path end def path @@path end def create_file(name, content) dirname = File.dirname(name) unless File.directory?(dirname) FileUtils.mkdir_p(dirname) end File.new("#{name}", 'w').close IO.write(name, content) puts("create #{name}") end def read_from_file(path) File.open(path).read end end Testing.start(ARGV)
# frozen_string_literal: true require 'pry' class Plant attr_reader :type def initialize(type) @type = type end def self.grow 'ai am class' end def grow if trees.include?(type) 'a tree' elsif grass.include?(type) 'a grass' elsif seaweed.include?(type) 'a seaweed' else 'unknown' end end private def trees %w[груша яблоня вишня слива дуб] end def grass %w[лютик ромашка роза лилия] end def seaweed %w[эгокропила линея остреопсис ундария перестая] end end
API::Engine.routes.draw do # API routes # Set APIVersion.new(version: X, default: true) for dafault API version scope module: :v1, constraints: APIVersion.new(version: 1, current: true), defaults: { format: 'json' } do with_options only: :index do |list_index_only| list_index_only.resources :domains list_index_only.resources :relations end with_options only: [:index, :show] do |list_show_only| list_show_only.resources :actors do resources :comments, only: [:index, :create] end list_show_only.resources :acts, path: 'actions' do resources :comments, only: [:index, :create] end list_show_only.resources :indicators, path: 'artifacts' do resources :comments, only: [:index, :create] end end with_options only: [:index, :update, :create, :destroy] do |list_index_only| list_index_only.resources :favourites end end end
module Autoprotocol module Util # Convert a Unit or volume string into its equivalent in microliters. # # === Parameters # # * vol : Unit, str # A volume string or Unit with the unit "nanoliter" or "milliliter" def self.convert_to_ul(vol) v = Unit.fromstring(vol) if v.unit == "nanoliter" v = Unit.new(v.value/1000, "microliter") elsif v.unit == "milliliter" v = Unit.new(v.value*1000, "microliter") elsif v.unit == "microliter" return v else raise ValueError, "The unit you're trign to convert to microliters is invalid" end v end # Convert a 384-well plate quadrant well index into its corresponding # integer form. # # "A1" -> 0 # "A2" -> 1 # "B1" -> 2 # "B2" -> 3 # # === Parameters # # * q : int, str # A string or integer representing a well index that corresponds to a # quadrant on a 384-well plate. def self.quad_ind_to_num(q) if q.is_a? String q = q.lower() end if ["a1", 0].include? q return 0 elsif ["a2", 1].include? q return 1 elsif ["b1", 24].include? q return 2 elsif ["b2", 25].include? q return 3 else raise ValueError.new "Invalid quadrant index." end end # Convert a 384-well plate quadrant integer into its corresponding well index. # # 0 -> "A1" or 0 # 1 -> "A2" or 1 # 2 -> "B1" or 24 # 3 -> "B2" or 25 # # === Parameters # # * q : int # An integer representing a quadrant number of a 384-well plate. # * human : bool, optional # Return the corresponding well index in human readable form instead of # as an integer if True. def self.quad_num_to_ind(q, human=false) if q == 0 if human return "A1" else return 0 end elsif q == 1 if human return "A2" else return 1 end elsif q == 2 if human return "B1" else return 24 end elsif q == 3 if human return "B2" else return 25 end else raise ValueError.new "Invalid quadrant number." end end end end
require 'dry/transaction' require 'yaml' module Indoctrinatr module Tools module ErrorChecker class TemplatePackErrorChecker include Dry::Transaction # class wide constants # needs to match indoctrinatr's TemplateField model VALID_PRESENTATIONS = %w[text textarea checkbox radiobutton dropdown date range file].freeze REQUIRES_AVAILABLE_OPTIONS = %w[dropdown checkbox radiobutton].freeze step :setup step :check_config_file_existence step :check_config_file_syntax step :check_attributes # TODO: check multiple variable name declaration (low-prio) private def setup(template_pack_name) path_name = Pathname.new(Dir.pwd).join template_pack_name config_file_path = path_name.join 'configuration.yaml' Success( { template_pack_name:, path_name:, config_file_path: } ) rescue StandardError => e Failure(e.message) end def check_config_file_existence(config) return Failure('The file configuration.yaml does not exist in the template_pack directory') unless File.exist? config[:config_file_path] Success(config) rescue StandardError => e Failure(e.message) end # YAML syntax check def check_config_file_syntax(config) puts 'Checking YAML syntax...' YAML.parse_file config[:config_file_path] puts 'YAML syntax ok!' Success(config) rescue YAML::SyntaxError => e # no program abort when this exception is thrown puts 'YAML syntax error in configuration.yaml, see error for details:' Failure(e.message) rescue StandardError => e Failure(e.message) end def check_attributes(config) configuration = ConfigurationExtractor.new(config[:template_pack_name]).call puts 'Checking attributes...' configuration.attributes_as_hashes_in_array.each_with_index do |attribute_hash, index| identifier = "Variable number #{index + 1}" # string for the user to localize variable with errors/warnings name_field = check_field_attribute attribute_hash, identifier, 'name' identifier = "Variable \"#{name_field}\"" if name_field != false check_presentation attribute_hash, identifier check_field_attribute attribute_hash, identifier, 'default_value' check_field_attribute attribute_hash, identifier, 'description' # idea: warning if no required attribute? end Success('Checking complete.') rescue StandardError => e Failure(e.message) end # false if something wrong, otherwise returns the key value def check_field_attribute(attribute_hash, field_identifier, key) unless attribute_hash.key? key puts "The #{field_identifier} has no #{key} type set!" return false end if attribute_hash[key].nil? || attribute_hash[key].empty? puts "The #{field_identifier} has an empty #{key}!" false else attribute_hash[key] end end def check_presentation(attribute_hash, identifier) presentation = check_field_attribute attribute_hash, identifier, 'presentation' return false unless presentation # check if it is one of the options puts "Not an allowed presentation option set for #{identifier}" unless VALID_PRESENTATIONS.include? presentation check_available_options attribute_hash, identifier, presentation if REQUIRES_AVAILABLE_OPTIONS.include? presentation check_presentation_range attribute_hash, identifier, presentation if presentation == 'range' end def check_available_options(attribute_hash, identifier, presentation_type) unless attribute_hash.key? 'available_options' puts "The #{identifier} has no available_options (needed for #{presentation_type} presentation)" return false end available_options = attribute_hash['available_options'] if available_options.nil? puts("available_options for #{identifier} is empty (needed for #{presentation_type} presentation)") false else puts("available_options for #{identifier} has only one option. That is useless.") if available_options.count(',') == 1 true end end def check_presentation_range(attribute_hash, identifier, presentation) puts "The #{identifier} has no start_of_range field (needed for #{presentation} presentation)" unless attribute_hash.key? 'start_of_range' puts "The #{identifier} has no end_of_range field (needed for #{presentation} presentation)" unless attribute_hash.key? 'end_of_range' # TODO: check for content end end end end end
class ItemsController < ApplicationController before_action :signed_in_administrator, only: [:new, :index, :edit, :update, :destory] def new @item = Item.new end def index @items = Item.where(lang: I18n.locale) end def create @item = Item.new(item_params) @item.save redirect_to items_path end def show @item = Item.find(params[:id]) @cuisine = Menu.find(@item.menu_id) end def edit @item = Item.find(params[:id]) end def update @item = Item.find(params[:id]) if @item.update_attributes(item_params) redirect_to items_path else render 'edit' end end def destroy Item.find(params[:id]).destroy redirect_to :back end private def item_params params.require(:item).permit(:price, :description, :menu_id, :restaurant_id, :lang) end end
require 'spec_helper' require 'rails_helper' RSpec.describe EstimationSessionsController, :type => :controller do describe 'estimationSession in general' do before do @project = FactoryGirl.create(:project) @serie = FactoryGirl.create(:serie) end it 'creating estimation' do estimation = @project.estimation_sessions.new estimation.serie = @serie expect(estimation.save).to be true end it 'hash is unique' do estimationnn = FactoryGirl.create(:estimationSession) a = EstimationSession.where(sharedLink: estimationnn.sharedLink).count expect(a).to be == 1 end end describe 'POST create', :type => :request do before do @project = FactoryGirl.create(:project) @serie = FactoryGirl.create(:serie) end it 'estimate story' do estimation = @project.estimation_sessions.new estimation.serie = @serie headers = { 'CONTENT_TYPE' => 'application/json' } post '/projects', '{ "name": "Project", "email": "a@a", "nickname": "tester", "serie": "Fibonacci", "stories": ["aa","bb"], "synchronous": true, "timebox_sync": [1,0], "consensusStrategy": "Average" }', headers actual_estimation_session = EstimationSession.find(session[:estimation_session_id]) story_id = actual_estimation_session.stories.first[:id] headers = { 'CONTENT_TYPE' => 'application/json' } url_for_get = '/estimation_sessions/' + actual_estimation_session.sharedLink.to_s parametros = '{"id": "' + actual_estimation_session.sharedLink.to_s + '"}' text_from_get = '' get url_for_get, parametros, headers text_to_post = '{ "id_story": "' + story_id.to_s + '", "story_estimation": "3", "id_estimation_session": "' + session[:estimation_session_id].to_s + '"}' post '/estimation_sessions/estimate_story', text_to_post, headers text_to_post = '{ "id_story": "' + story_id.to_s + '"}' post '/estimation_sessions/final_estimation', text_to_post, headers url_for_get = '/estimation_sessions/' + actual_estimation_session.sharedLink.to_s parametros = '{"id": "' + actual_estimation_session.sharedLink.to_s + '"}' get url_for_get, parametros, headers estimated_story = actual_estimation_session.stories.find(story_id) end it 'test show without user and anonymous user' do estimation = @project.estimation_sessions.new estimation.serie = @serie headers = { 'CONTENT_TYPE' => 'application/json' } post '/projects', '{ "name": "Project", "email": "a@a", "nickname": "tester", "serie": "Fibonacci", "stories": ["aa","bb"], "synchronous": true, "timebox_sync": [1,0], "consensusStrategy": "Average" }', headers actual_estimation_session = EstimationSession.find(session[:estimation_session_id]) url_for_get = '/estimation_sessions/' + actual_estimation_session.sharedLink.to_s parametros = '{"id": "' + actual_estimation_session.sharedLink.to_s + '"}' text_from_get = '' get url_for_get, parametros, headers end end end
# http://www.mudynamics.com # http://labs.mudynamics.com # http://www.pcapr.net require 'mu/pcap/reader' require 'stringio' require 'zlib' module Mu class Pcap class Reader # Reader for HTTP family of protocols (HTTP/SIP/RTSP). # Handles message boundaries and decompressing/dechunking payloads. class HttpFamily < Reader FAMILY = :http FAMILY_TO_READER[FAMILY] = self CRLF = "\r\n" def family FAMILY end def do_record_write bytes, state=nil return if not state if bytes =~ RE_REQUEST_LINE method = $1 requests = state[:requests] ||= [] requests << method end end private :do_record_write RE_CONTENT_ENCODING = /^content-encoding:\s*(gzip|deflate)/i RE_CHUNKED = /Transfer-Encoding:\s*chunked/i RE_HEADERS_COMPLETE = /.*?\r\n\r\n/m # Request line e.g. GET /index.html HTTP/1.1 RE_REQUEST_LINE = /\A([^ \t\r\n]+)[ \t]+([^ \t\r\n]+)[ \t]+(HTTP|SIP|RTSP)\/[\d.]+.*\r\n/ # Status line e.g. SIP/2.0 404 Authorization required RE_STATUS_LINE = /\A((HTTP|SIP|RTSP)\/[\d.]+[ \t]+(\d+))\b.*\r\n/ RE_CONTENT_LENGTH = /^(Content-Length)(:\s*)(\d+)\r\n/i RE_CONTENT_LENGTH_SIP = /^(Content-Length|l)(:\s*)(\d+)\r\n/i def do_read_message! bytes, state=nil case bytes when RE_REQUEST_LINE proto = $3 when RE_STATUS_LINE proto = $2 status = $3.to_i if state requests = state[:requests] ||= [] if requests[0] == "HEAD" reply_to_head = true end if status > 199 # We have a final response. Forget about request. requests.shift end end else return nil # Not http family. end # Read headers if bytes =~ RE_HEADERS_COMPLETE headers = $& rest = $' else return nil end message = [headers] # Read payload. if proto == 'SIP' re_content_length = RE_CONTENT_LENGTH_SIP else re_content_length = RE_CONTENT_LENGTH end if reply_to_head length = 0 elsif headers =~ RE_CHUNKED # Read chunks, dechunking in runtime case. raw, dechunked = get_chunks(rest) if raw length = raw.length payload = raw else return nil # Last chunk not received. end elsif headers =~ re_content_length length = $3.to_i if rest.length >= length payload = rest.slice(0,length) else return nil # Not enough bytes. end else # XXX. When there is a payload and no content-length # header HTTP RFC says to read until connection close. length = 0 end message << payload # Consume message from input bytes. message_len = headers.length + length if bytes.length >= message_len bytes.slice!(0, message_len) return message.join else return nil # Not enough bytes. end end private :do_read_message! # Returns array containing raw and dechunked payload. Returns nil # if payload cannot be completely read. RE_CHUNK_SIZE_LINE = /\A([[:xdigit:]]+)\r\n?/ def get_chunks bytes raw = [] dechunked = [] io = StringIO.new bytes until io.eof? # Read size line size_line = io.readline raw << size_line if size_line =~ RE_CHUNK_SIZE_LINE chunk_size = $1.to_i(16) else # Malformed chunk size line $stderr.puts "malformed size line : #{size_line.inspect}" return nil end # Read chunk data chunk = io.read(chunk_size) if chunk.size < chunk_size # malformed/incomplete $stderr.puts "malformed/incomplete #{chunk_size}" return nil end raw << chunk dechunked << chunk # Get end-of-chunk CRLF crlf = io.read(2) if crlf == CRLF raw << crlf else # CRLF has not arrived or, if this is the last chunk, # we might be looking at the first two bytes of a trailer # and we don't support trailers (see rfc 2616 sec3.6.1). return nil end if chunk_size == 0 # Done. Return raw and dechunked payloads. return raw.join, dechunked.join end end # EOF w/out reaching last chunk. return nil end end end end end
class CreateInvoices < ActiveRecord::Migration[5.2] def change create_table :invoices do |t| t.float :price t.string :buyer_tax_number t.string :buyer_name t.string :buyer_address t.references :job t.timestamps end end end
#!/usr/bin/env ruby require 'gli' begin # XXX: Remove this begin/rescue before distributing your app require 'markedblog' rescue LoadError STDERR.puts "In development, you need to use `bundle exec bin/markedblog` to run your app" exit 64 end include GLI::App program_desc 'Create a static blog from MultiMarkdown files.' version Markedblog::VERSION config_file '.markedBlog.rc' desc 'Compile the blog from the specified directory.' default_value './' arg_name '/to/compile' flag [:d,:directory] desc 'Output path.' default_value '../output' arg_name '/output/dir' flag [:o,:output] desc 'Create a new, empty blog structure, with no framework.' arg_name 'Describe arguments to create here' command :create do |c| c.desc 'Describe a switch to create' c.switch :s c.desc 'Describe a flag to create' c.default_value 'default' c.flag :f c.action do |global_options,options,args| # Your command logic here # If you have any errors, just raise them # raise "that command made no sense" puts "create command ran" end end desc 'Create a new, empty blog framework.' arg_name 'Describe arguments to scaffold here' command :scaffold do |c| c.action do |global_options,options,args| puts "scaffold command ran" end end desc 'Compile the current blog into static files.' arg_name 'Describe arguments to compile here' command :compile do |c| c.action do |global_options,options,args| puts "compile command ran" end end desc 'Create a new blog post or page.' arg_name 'ArticleType' command :new do |c| c.action do |global_options,options,args| puts "new command ran with #{args}" end end desc 'Change the way the app runs for your current blog.' arg_name 'Section.settting' command :settings do |s| s.action do |global_options,options,args| puts "settings command ran" end end pre do |global,command,options,args| # Pre logic here # Return true to proceed; false to abourt and not call the # chosen command # Use skips_pre before a command to skip this block # on that command only true end post do |global,command,options,args| # Post logic here # Use skips_post before a command to skip this # block on that command only end on_error do |exception| # Error logic here # return false to skip default error handling true end exit run(ARGV)
# main class to store event data incl. basic details and ticket purchase info # also stores related students, posts, ads, announcements # an event is associated with one club, and can only be created by an Admin. class Event < ActiveRecord::Base belongs_to :club, class_name: "Club" has_many :ticket_reservations, foreign_key: "event_id", dependent: :destroy has_many :students, through: :ticket_reservations, source: :student has_many :posts, foreign_key: "event_id", dependent: :destroy has_many :ads, foreign_key: "event_id", dependent: :destroy has_many :announcements, foreign_key: "event_id", dependent: :destroy has_attached_file :banner, styles: {thumb: "100x100#"}, default_url: "/images/:style/missing.png" validates_attachment :banner, presence: true, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }, size: {in: 0..1.megabytes} validates :name, presence:true validates :start, presence:true validates :end, presence:true validates :location, presence:true, length: {minimum: 4} validates :description, presence:true, length: {maximum: 500} validates :ticket_price, presence:true, numericality: :true validates :initial_tickets_avail, presence:true, numericality: {only_integer: true} validates :ticket_purchase_instructions, presence:true, length: {maximum: 140} validates :sales_start, presence:true validates :sales_end, presence:true validates :conditions, presence:true, length: {maximum: 200} validates :banner, presence:true validate :valid_start, :valid_end, :valid_sales_start, :valid_sales_end validate :start_has_time, :end_has_time, :sales_start_has_time, :sales_end_has_time validate :start_in_future, :sales_start_in_future validate :end_after_start, :sales_end_after_start default_scope -> {order('start ASC')} # THE FOLLOWING ARE ALL DATETIME VALIDATIONS # def start_has_time errors.add(:start, " must have a time. Time cannot be midnight.") unless \ has_time?(self.start) end def end_has_time errors.add(:end, " must have a time. Time cannot be midnight.") unless \ has_time?(self.end) end def sales_start_has_time errors.add(:sales_start, " must have a time. Time cannot be midnight.") unless \ has_time?(self.sales_start) end def sales_end_has_time errors.add(:sales_end, " must have a time. Time cannot be midnight.") unless \ has_time?(self.sales_end) end def has_time?(dt) dt.strftime("%H:%M") != "00:00" rescue NoMethodError false end def valid_start errors.add(:start, " date/time not valid. Please enter in format DD/MM/YYYY HH:MM") unless \ valid_datetime?(self.start) end def valid_end errors.add(:end, " date/time not valid. Please enter in format DD/MM/YYYY HH:MM") unless \ valid_datetime?(self.end) end def valid_sales_start errors.add(:sales_start, " date/time not valid. Please enter in format DD/MM/YYYY HH:MM") unless \ valid_datetime?(self.sales_start) end def valid_sales_end errors.add(:sales_end, " date/time not valid. Please enter in format DD/MM/YYYY HH:MM") unless \ valid_datetime?(self.sales_end) end def valid_datetime?(dt) str = dt.strftime("%d/%m/%Y %H:%M") DateTime.parse(str) true rescue ArgumentError, NoMethodError false end def start_in_future if !self.start.nil? errors.add(:start, " cannot be in the past.") unless self.start > DateTime.now end end def sales_start_in_future if !self.sales_start.nil? errors.add(:sales_start, " cannot be in the past.") unless self.sales_start > DateTime.now end end def end_after_start if !self.start.nil? and !self.end.nil? errors.add(:end, " cannot be before start") unless self.end > self.start end end def sales_end_after_start if !self.sales_start.nil? and !self.sales_end.nil? errors.add(:sales_end, " cannot be before start") unless self.sales_end > self.sales_start end end end
require 'boxzooka/base_request' require 'boxzooka/landed_quote_request_item' module Boxzooka class LandedQuoteRequest < BaseRequest root node_name: 'LandedQuote' # ISO 4217 scalar :currency # ISO 3166-1 Alpha-2 scalar :destination_country_code # Country-specific. For US: use 2 char state code. scalar :destination_province collection :products, entry_field_type: :entity, entry_type: LandedQuoteRequestItem, entry_node_name: 'Item' # ISO 3166-1 Alpha-2 scalar :origin_country_code # Country-specific. For US: use 2 char state code. scalar :origin_province end end
class WoundSerializer < ActiveModel::Serializer belongs_to :people has_many :treatments attributes :name, :description, :img_url, :location, :person_id, :treatments end
#### # # Letter # # Letter is the association between Invoice and InvoiceText # #### # class Letter < ApplicationRecord belongs_to :invoice belongs_to :invoice_text validates :invoice, :invoice_text, presence: true end
class MakersController < ApplicationController def new end def create @maker = Maker.new(maker_params) @maker.save redirect_to @maker end def show @maker = Maker.find(params[:id]) respond_to do |format| format.html format.json{ render :json => @maker.to_json } end end def edit @maker = Maker.find(params[:id]) end def update @maker = Maker.find(params[:id]) if @maker.update(maker_params) redirect_to @maker else render 'edit' end end def destroy @maker = Maker.find(params[:id]) @maker.destroy redirect_to makers_path end def index @makers = Maker.all end private def maker_params params.require(:maker).permit(:name, :role, :bio) end end
# coding: utf-8 class CommunityPresenter < BasePresenter include ActionView::Helpers include ApplicationHelper presents :community def title raw link_to(article.title, show_community_article_url(article.community, article)) end def text raw truncate(strip_tags(article.body), length: 140, omission: '.....') end def metadata out = [] out << community.organization out << community.dept out << community.title return raw out.join(" &nbsp; ") end end
class PostSearch attr_accessor :keywords, :category, :per_page def initialize(params = {}) @keywords = params[:keywords] ? params[:keywords].gsub(/[^a-zA-Z0-9\s]/, '').split(/\s/) : [] # @per_page = 15 # @page = params[:page] || 1 @category_id = params[:category_id] || nil # @category = Category.find_by_id(@category_id) @query_string = [] @query_params = [] end def query if @query_string.blank? "" else [@query_string.join(' AND '), *@query_params] end end def add_keywords return if @keywords.empty? temp = @keywords.collect do |term| @query_params << "%#{term}%" "page_title LIKE ?" end @query_string << "(#{ temp.join(' AND ') })" end def add_category return if @category_id.blank? @query_params << @category_id @query_string << 'categories.id = ?' end def build_query add_keywords add_category end def go return [] if @query_string.nil? build_query if @query_string.empty? OldTextFile.all else # OldTextFile.includes(:category).where(query).page(@page).per(@per_page) OldTextFile.includes(:category).where(query) end end end
package "midonet-cluster" do action :install end file "/etc/midonet/midonet.conf" do action :edit # group "root" # user "root" block do |content| nsdb_binds = node[:nsdb_ips].map{|x| "#{x}:2181"}.join(?,) content.sub!(/^\#?zookeeper_hosts = .*$/, "zookeeper_hosts = #{nsdb_binds}") end end execute "Configure access to the NSDB (zookeeper)" do user "root" nsdb_binds = node[:nsdb_ips].map{|x| "#{x}:2181"}.join(?,) command "cat <<EOF | mn-conf set -t default zookeeper { zookeeper_hosts = \"#{nsdb_binds}\" } EOF " end execute "Configure access to the NSDB (cassandra)" do user "root" nsdb_binds = node[:nsdb_ips].map{|x| "#{x}:2181"}.join(?,) command "cat <<EOF | mn-conf set -t default cassandra { servers = \"#{node[:nsdb_ips].join(?,)}\" } EOF " end execute "Configure Keystone access" do user "root" command "cat <<EOF | mn-conf set -t default cluster.auth { provider_class = \"org.midonet.cluster.auth.keystone.KeystoneService\" admin_role = \"admin\" keystone.domain_id = \"\" keystone.domain_name = \"default\" keystone.tenant_name = \"admin\" keystone.admin_token = \"#{node[:keystone_admin_token]}\" keystone.host = #{node[:controller_node_ip]} keystone.port = 35357 } EOF " end service "midonet-cluster.service" do action [:enable, :restart] end
Ransack::Helpers::FormHelper.module_eval do def link_name(label_text, dir) ERB::Util.h(label_text).html_safe end end
class AddTypeCdToUsers < ActiveRecord::Migration def change add_column :users, :type_cd, :string, limit: 20, null: false, after: :uuid end end
require 'str_to_seconds' class Title < ApplicationRecord belongs_to :category belongs_to :notice, optional: true belongs_to :office, optional: true has_many :records validates :name, presence: true, :uniqueness => { :scope => [:category] } validates :category, presence: true validates :description, presence: true, allow_nil: true validates :n_available, presence: true, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true validates :notice_id, presence: true, allow_nil: true validates :loan_length_seconds, presence: true, allow_nil: false #validates :office_id, presence: true, allow_nil: true validate :office_id_and_n_available after_initialize :initialize_default_loan def n_in unless self.n_available.nil? # return zero instead of a negative number [self.n_available - self.n_out, 0].max end end def n_out self.records.where(in: nil).length end def available? if !self.enabled # if a title is disabled, there are none available for checkout return false elsif self.n_available.nil? # if a title has a nil n_available, there are an infinite number available for checkout return true end # if the title is enabled, and has a limited numeber available, the title # is enabled if and only if the number in stock is 1 or more return n_in > 0 end def loan_length self.loan_length_seconds.to_human_time unless self.loan_length_seconds.nil? end def loan_length=(length) self.loan_length_seconds = length.to_seconds end def average_loan_time_seconds unless ActiveRecord::Base.connection.instance_of? ActiveRecord::ConnectionAdapters::Mysql2Adapter # unfortunately, this is not database agnostic, and this will only # (as far as I know) work using MySQL return nil end returned_records = records.where.not(in:nil) if returned_records.present? return returned_records.average('unix_timestamp(`in`) - unix_timestamp(`out`)').round else return nil end end def average_loan_time unless average_loan_time_seconds.nil? average_loan_time_seconds.to_human_time end end def options # split string on newlines or commas, then remove whitespace from each # option if options_str.nil? or options_str.empty? # return an empty list so that .in? or .include? doesn't complain return [] else return options_str.split("\n") end end def options=(options_array) options_array.each { |option| option.strip! } write_attribute :options_str, options_array.join("\n") end def options_str=(new_options_str) self.options = new_options_str.split("\n") end def popularity # return the total number of checkouts for sorting purposes Rails.cache.fetch("#{cache_key}/popularity", expires_in: 24.hours) do self.records.length end end ############################################################################# private ##################################################################### ############################################################################# # private # def category_must_be_enabled # if enabled and !category.enabled # errors.add(:enabled, "cannot be set if the title's category is not enabled") # end # end # private def initialize_default_loan if self.category and self.loan_length_seconds.nil? and self.new_record? self.loan_length_seconds = self.category.loan_length_seconds end end #private def office_id_and_n_available # validation; checks that n_available is only set when office_id is set if !n_available.nil? and office_id.nil? errors.add(:n_available, "is not a valid option for this title") end end end
require 'rails_helper' RSpec.describe ActiveRecordMultipleQueryCache::Rails5QueryCache do next if ActiveRecord.gem_version < Gem::Version.new('5.0.0') let(:instance) { described_class.new(active_record_base_class) } let(:active_record_base_class) { ActiveRecord::Base } describe '#run' do subject do -> { instance.run } end after do active_record_base_class.connection.disable_query_cache! end it { is_expected.to change(active_record_base_class.connection, :query_cache_enabled).from(false).to(true) } end describe '#complete' do subject do -> { instance.complete([caching_pool, caching_was_enabled]) } end before do active_record_base_class.connection.enable_query_cache! end after do active_record_base_class.connection.disable_query_cache! end let(:caching_pool) { active_record_base_class.connection_pool } let(:caching_was_enabled) { false } it 'disables query_cache' do is_expected.to change(active_record_base_class.connection, :query_cache_enabled).from(true).to(false) end end end
require 'alphavantagerb' module AlphavantageClient DEFAULT_WAITING_TIME = 5 DEFAULT_RETRY = 10 def alphavantage_client AlphavantageClient.alphavantage_client end def alphavantage_config AlphavantageClient.alphavantage_config end def self.alphavantage_config return @alphavantage_config if @alphavantage_config @alphavantage_config = {} @alphavantage_config[:verbose] = Settings.alphavantage.verbose || false @alphavantage_config[:waiting_time] = Settings.alphavantage.waiting_time || DEFAULT_WAITING_TIME @alphavantage_config[:retry] = Settings.alphavantage.retry || DEFAULT_RETRY @alphavantage_config end def self.alphavantage_client return @alphavantage_client if @alphavantage_client key = ENV['ALPHAVANTAGE_KEY'] rescue "demo" @alphavantage_client = Alphavantage::Client.new key: key, verbose: alphavantage_config[:verbose] @alphavantage_client end def daily_stock symbol attempts = 0 while true begin stock = alphavantage_client.stock symbol: symbol return stock.timeseries outputsize: "full" rescue Alphavantage::Error => ex attempts += 1 Rails.logger.warn "Attempts #{attempts} failed for #{symbol}" raise ex if attempts == alphavantage_config[:retry] Rails.logger.info "Waiting #{alphavantage_config[:waiting_time]} seconds" sleep alphavantage_config[:waiting_time] end end end end
class AddErrorbundle < ActiveRecord::Migration def self.up create_table "errorbundles" do |t| t.column :offering_id, :integer t.column :comment, :string t.column :name, :string t.column :content_type, :string t.column :data, :binary, :limit => 4.megabyte t.column :created_at, :timestamp end end def self.down drop_table "errorbundles" end end
require 'spec_helper' resource "Notes" do let(:user) { users(:owner) } let(:note) { events(:note_on_hdfs_file) } let(:hdfs_file) { HdfsEntry.files.first } let(:attachment) { attachments(:sql) } before do log_in user end post "/notes" do parameter :body, "Text body of the note" parameter :entity_type, "Type of object the note is being posted on" parameter :entity_id, "Id of the object the note is being posted on" parameter :is_insight, "Promote this note to an insight?" let(:body) { note.body } let(:gpdb_instance) { gpdb_instances(:owners) } let(:entity_type) { "greenplum_instance" } let(:entity_id) { gpdb_instance.id } example_request "Post a new note/insight on an entity" do status.should == 201 end end put "/notes/:id" do parameter :id, "Note id" parameter :body, "New text body of the note" required_parameters :id let(:id) { note.id } let(:body) { "New text" } example_request "Changes the body of a note" do status.should == 200 end end delete "/notes/:id" do parameter :id, "Note id" required_parameters :id let(:id) { note.id } example_request "Delete a note" do status.should == 200 end end post "/notes/:note_id/attachments" do parameter :note_id, "Note id" parameter :contents, "File contents" required_parameters :note_id, :contents let(:note_id) { note.id } let(:contents) { test_file("small1.gif") } example_request "Attach the contents of a file to a note" do status.should == 200 end end post "/notes/:note_id/attachments" do parameter :note_id, "Note id" parameter :svg_data, "SVG File contents" required_parameters :note_id, :svg_data let(:note_id) { note.id } let(:svg_data) { test_file("SVG-logo.svg").read } example_request "Attach a visualization to a note" do status.should == 200 end end get "/notes/:note_id/attachments/:id" do parameter :note_id, "Note id" parameter :id, "Attachment id" required_parameters :note_id, :id let(:note_id) { note.id } let(:id) { attachment.id } example_request "Get the contents of an attachment" do status.should == 200 end end end
class WeInvite < ActionMailer::Base def our_invite(guest) @guest = guest mail(:to => @guest.email, :subject => "Wedding Invitation", :from => "weddinginviteon28@gmail.com") end end
class GroupEnrollmentsController < WebApplicationController before_action :set_group_enrollment, only: [:destroy] def create group = GroupOffering.find( group_enrollment_params[:group_offering_id] ).group @group_enrollment = GroupEnrollment.new( group_enrollment_params ) if @group_enrollment.save respond_to do |format| format.html { redirect_to group, notice: 'Asignado a taller' } format.json { head 201 } end else respond_to do |format| format.html { redirect_to group, alert: 'No se pudo inscribir' } format.json { head 402 } end end end def destroy group = @group_enrollment.group_offering.group @group_enrollment.destroy respond_to do |format| format.html { redirect_to group, notice: 'Niño desasignado de taller' } format.json { head :no_content } end end private def set_group_enrollment @group_enrollment = GroupEnrollment.find( params[:id] ) end def group_enrollment_params params.require( :group_enrollment ).permit( :group_offering_id, :enrolled_type, :enrolled_id ) end end
require 'test_helper' class ArticlesCreateTest < ActionDispatch::IntegrationTest def setup @user = users(:stacy) @article = articles(:one) end test "create article after succesfully logged in" do get new_article_path assert_not is_logged_in? get login_path assert_response :success assert_template 'sessions/new' post login_path, session: {email: @user.email, password: 'password'} assert is_logged_in? assert_redirected_to @user follow_redirect! assert_response :success assert_template 'users/show' post articles_path, article: { title: @article.title, text: @article.text} assert_redirected_to root_path follow_redirect! assert_response :success end end
class RequestController < ApplicationController before_action :require_user #This method will return all the requests for the user logged in. def index @requests = Request.where(user_id: session[:user_id]).where(is_completed: 0) end def new @request = Request.new end def show @request = Request.find(params[:id]) @comment = Comment.new end def create @request = Request.create(request_params) redirect_to project_path(@request.project_id) end def request_params params.require(:request).permit(:name, :description, :num_of_hours, :project_id) end #This method will assign a user to a particular request def update request = Request.find(params[:id]) request.update(user_id: params[:user_id]) #So this method (update) can be called through ajax. render :nothing => true end #Complete the request def finish request = Request.find(params[:request_id]) request.update(is_completed: 1) redirect_to '/my_requests' end #Remove the request def destroy Request.find(params[:id]).destroy redirect_to '/my_requests' end end
module Api class BaseController < ::ApplicationController respond_to :json before_filter :require_json_format protect_from_forgery except: [:routing_error] private def require_json_format unless request.format == "json" render json: {error: "Only json format is supported"}, status: :bad_request return false end true end private :require_json_format def routing_error render json: nil, status: 400 end private :routing_error def respond_error(response, status = :unprocessable_entity) respond_invalid({errors: {key: response}}, status) end private :respond_error def respond_invalid(response, status = :unprocessable_entity) render json: response, status: status end private :respond_invalid def unauthorized respond_error('unauthorized') end private :unauthorized def account_doesnt_exist session.sign_out respond_error('sessionNoFBdata') end private :account_doesnt_exist end end
require "curses" include Curses class CursesScreen def initialize game init_screen @game = game end def play grid begin crmode while true do print_step grid sleep 0.5 grid = @game.step grid end ensure close_screen end end def print_step grid grid.cells { | x, y | setpos(y, x) if grid.alive? x, y then addstr("*") else addstr(".") end } refresh end end
class Venue attr_reader :name, :capacity, :patrons def initialize(name, capacity) @name = name @capacity = capacity @patrons = [] end def add_patron(name) @patrons << name end def yell_at_patrons yelled = [] @patrons.each do |name| yelled << name.upcase end yelled end def over_capacity? return false if @patrons.length <= @capacity return true if @patrons.length > @capacity end def kick_out return false if @patrons.length <= @capacity if @patrons.length > @capacity until @patrons.length == @capacity do @patrons.pop end end end end
class AddTimestampsToPortfoliosStocks < ActiveRecord::Migration def self.up # Or `def up` in 3.1 change_table :portfolios_stocks do |t| t.timestamps end end def self.down # Or `def down` in 3.1 remove_column :portfolios_stocks, :created_at remove_column :portfolios_stocks, :updated_at end end