text
stringlengths
10
2.61M
# This is how cancan controls authorization. For more details look at https://github.com/ryanb/cancan class AdminAbility include CanCan::Ability # This method sets up the user's abilities to view admin pages # look at https://github.com/ryanb/cancan for more info def initialize(user) user ||= User.new # guest user will not be allowed in the admin section alias_actions if user.super_admin? can :manage, :all elsif user.admin? || user.contractor? #can :manage, :all #can :read, :all #can :view_users, User do # user.admin? #end #authorize! :view_users, @user #can :create_users, User do # user.super_admin? #end #authorize! :create_users, @user #can :create_orders, User if user.trial || user.unsubscribed unless user.unsubscribed can [:make], Product if user.products.count < 1 end can [:read, :change], Product, contractor_id: user.id else can :manage, Product, contractor_id: user.id end can :manage, Order, contractor_id: user.id can :manage, Shipment, order: {contractor_id: user.id} can :manage, ImageGroup, product: {contractor_id: user.id} can :manage, Property can :manage, Invoice if user.has_balance? can :manage, Requests::Balance, user_id: user.id can [:read, :make, :cancel], Requests::Transaction, balance_id: user.balance.id can :read, Requests::Credit can [:read, :make, :cancel], Requests::Withdraw can [:read], Requests::Refund, transaksi: {balance_id: user.balance.id} end can :manage, :overview end end protected def alias_actions alias_action :index, :show, :to => :read alias_action :edit, :update, to: :change alias_action :new,:create, to: :make alias_action :destroy, to: :delete alias_action :index, :show, :new, :create, :edit, :update, :destroy, to: :crud end end
class CreateFilterTypesRestaurant < ActiveRecord::Migration def change create_table :filter_types_restaurants, :id => false do |t| t.integer :filter_type_id t.integer :restaurant_id t.timestamps end add_column :filters, :filter_type_id, :integer end end
class AddReferrerCategoryToSessions < ActiveRecord::Migration def self.up add_column :sessions, :referrer_category, :string, :limit => 50 end def self.down remove_column :sessions, :referrer_category end end
class Contact < ActiveRecord::Base validates :name, length: {minimum: 6} validates :email, presence: true end
class ChargeFailed def call(event) failure_code = event['data']['object']['failure_code'] store_order_id = event['data']['object']['metadata']['store_order_id'] order_id = event['data']['object']['metadata']['order_id'] if failure_code && (store_order_id.present? || order_id.present?) record = store_order_id.present? ? StoreOrder.where(id: store_order_id).first : Order.where(id: order_id).first if record.present? record.stripe_webhook_events.create(stripe_type: event['type'], stripe_failure_code: failure_code, stripe_id: event['id'], data: event['data'].as_json) record.update(status: :failure) if failure_code == 'card_declined' puts "CARD DECLINED FOR" + record.inspect elsif failure_code == 'insufficient_funds' puts "REFUND FROM: " + record.inspect + " FAILED, AND MONEY WITHDRAWN FROM PLATFORM ACCOUNT" end end end end end
Gem::Specification.new do |s| s.name = 'lazy_initializer' s.version = '0.0.1' s.date = '2013-06-08' s.summary = "Lazy initializer helper class" s.authors = ["James Kassemi"] s.email = 'james@atpay.com' s.files = `git ls-files`.split($/) s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.homepage = "https://atpay.com" end
class EventSignup < ApplicationRecord validates_presence_of :event_slug validates_presence_of :snowflake def event Event.find_by(slug: self.event_slug) end def user User.find_or_create_by!(uid: self.snowflake) end def deck if self.sideboard.present? decklist = self.mainboard + "\n" + self.sideboard else decklist = self.mainboard end DeckParser.new($CardDatabase, decklist).deck end end
module ApiResponseCache class Config attr_accessor :refresh_by_request_params, :cache_by_headers def initialize @refresh_by_request_params = false end def refresh_by_request_params? @refresh_by_request_params end end end
class DropDefaultTypeOnAddresses < ActiveRecord::Migration def change change_column_default :addresses, :type, default: "" end end
# frozen_string_literal: true require 'spec_helper' describe RailwayOperation::Visualizer do let(:operation1) do op = RailwayOperation::Operation.new(:sample) op.alias_tracks('Operation 1' => 0, 'Operation 2' => 1) op.add_step(0, :method1) op.add_step(0, :method2) op.add_step(0, :method3) op.add_step(1, :method4) op.add_step(1, :method5) op.add_step(1, :method6) op end it 'renders graph' do expect(described_class.new(operation: operation1).render).to be_nil end end
source "https://rubygems.org" git_source(:github) { |name| "https://github.com/#{name}.git" } # Specify your gem's dependencies in sentry-ruby.gemspec gemspec gem "sentry-ruby", path: "../sentry-ruby" gem "sentry-rails", path: "../sentry-rails" gem "rake", "~> 12.0" gem "rspec", "~> 3.0" gem 'simplecov' gem "simplecov-cobertura", "~> 1.4" gem "rexml" # https://github.com/flavorjones/loofah/pull/267 # loofah changed the required ruby version in a patch so we need to explicitly pin it gem "loofah", "2.20.0" if RUBY_VERSION.to_f < 2.5 sidekiq_version = ENV["SIDEKIQ_VERSION"] sidekiq_version = "6.0" if sidekiq_version.nil? gem "sidekiq", "~> #{sidekiq_version}" gem "rails" if RUBY_VERSION.to_f >= 2.6 gem "debug", github: "ruby/debug", platform: :ruby gem "irb" end gem "pry"
require "test_helper" describe User do let(:user) { users(:jane) } it "user name must be valid" do name = users(:jane) valid_user = user.valid? expect(valid_user).must_equal true end describe "validations" do it "requires a name" do user.name = "" valid_user = user.valid? expect(valid_user).must_equal false expect(user.errors.messages).must_include :name expect(user.errors.messages[:name]).must_equal ["can't be blank"] end it "requires a unique name" do duplicate_user = User.new(name: user.name) expect(duplicate_user.save).must_equal false expect(duplicate_user.errors.messages).must_include :name expect(duplicate_user.errors.messages[:name]).must_equal ["has already been taken"] end end describe "relationshps" do it "has many votes" do expect(user).must_respond_to :votes end end end # outermost describe
require File.dirname(__FILE__) + '/../test_helper' class ProjectTest < Test::Unit::TestCase fixtures :projects, :companies, :users, :customers def setup @project = projects(:test_project) end # Replace this with your real tests. def test_truth assert_kind_of Project, @project end def test_after_create_without_forum p = Project.new p.name = "a" p.owner = users(:admin) p.company = companies(:cit) p.customer = customers(:internal_customer) p.create_forum = 0 p.save assert_not_nil p.forums assert_equal 0, p.forums.size end def test_after_create_with_forum p = Project.new p.name = "a" p.owner = users(:admin) p.company = companies(:cit) p.customer = customers(:internal_customer) p.create_forum = 1 p.save assert_not_nil p.forums assert_equal 1, p.forums.size assert_kind_of Forum, p.forums.first assert_equal "Internal / a", p.forums.first.name end def test_validate_name p = Project.new p.owner = users(:admin) p.company = companies(:cit) p.customer = customers(:internal_customer) assert !p.save assert_equal 1, p.errors.size assert_equal "can't be blank", p.errors['name'] end def test_full_name assert_equal "Internal / Test Project", @project.full_name end def test_to_css_name assert_equal "test-project internal", @project.to_css_name end end
class Api::UsersController < ApplicationController skip_before_action :verify_authenticity_token def index @users = User.all render json: @users end def create @user = User.new(user_params) if @user.save render json: @user else render json: { errors: {message: "this user could not be saved."}} end end private def user_params params.require(:user).permit(:name, :weight, :height, :bmi, :weekly_target, :weight_goal, :calorie_allot) end end
class Edition < ActiveRecord::Base has_and_belongs_to_many :works belongs_to :publisher #A nice title for the Edition model def nice_title (title || work[0].nice_title) + " (#{publisher.name}, #{year})" end #Determining all editions for a list of works def self.of_works(works) works.map {|work| work.editions}.flatten.uniq end end
class VideosController < ApplicationController include VideosHelper def create result = download_video(params[:video_id]) if result[:success] render json: result[:model] else render json: gen_error_response(404, result[:reason]), status: 404 end end def show @video = Video.find_by_video_id(params[:video_id]) if @video.present? render json: @video.to_json else render json: gen_error_response(404, "Video not found(You should create video before)"), status: 404 end end def download @video = Video.find_by_video_id(params[:video_id]) if @video.present? audio_path = File.join(Rails.root, 'tmp', 'cache', 'downloads', @video.video_id, "#{@video.video_id}.mp3") send_file audio_path, :type => 'audio/mp3' else render json: gen_error_response(412, "You should create video before download"), status: 412 end end end
require 'spec_helper' describe Hero do it 'can return if a hero is trained (true or false)' do not_trained_hero = (1..2).to_a.map {|number| Hero.create(name: "hero #{number}", trained: false ) } trained_hero = Hero.create({name: "trained hero", trained: true}) expect(Hero.not_trained).to eq not_trained_hero end end
class StoreController < ApplicationController before_filter :set_cart def index @hot_selling_products = LineItem.count(:group => :product_id).sort_by{|id, count| -count }[0.3].map{|id, count| Product.find(id)} @new_item = Product.recent(1) @products = Product.for_sale.paginate :page => params[:page], :per_page => 3 end def save_order @order = Order.new(params[:order]) @order.add_line_items_from_cart(@cart) if @order.save @cart.empty! # メール送信 Notifier.ordered(@order).deliver redirect_to store_path, :notice => "ご注文ありがとうございます" else render checkout_path end end def checkout if @cart.nil? || @cart.items.empty? redirect_to store_path, :notice => "カートは現在空です" end @order = Order.new end def add_to_cart #@product = Product.find(params[:id]) product = Product.find(params[:id]) @cart.add_product(product) #redirect_to store_path, :notice => "#{@product.name}が買い物カゴに追加されました" respond_to do |format| format.js end rescue ActiveRecord::RecordNotFound logger.error("無効な商品#{params[:id]}にアクセスしようとしました") redirect_to store_path, :notice => "無効な商品です" end def empty_cart @cart.empty! redirect_to store_path, :notice => "カートは現在空です" end private def current_cart session[:cart] ||= Cart.new # if session[:cart].nil? # Cart.new # else # session[:cart] # end end def set_cart @cart = current_cart end end
require 'rails_helper' RSpec.describe User, type: :model do it 'should have many showings' do should have_many(:showings) end it 'creates a user' do user = User.create!(name: 'agent1', email: 'foo@foo.com') expect(user.email).to include('foo@foo.com') end it 'creates a user showing' do time = Time.zone.now user = User.create!(name: 'agent1', email: 'foo@foo.com') showing = Showing.create!(start_time: time, user: user) expect(user.showings.length).to eq(1) end end
# encoding: UTF-8 require 'spec_helper' require 'yt/models/video' describe Yt::Video, :device_app do subject(:video) { Yt::Video.new id: id, auth: $account } context 'given someone else’s video' do let(:id) { '9bZkp7q19f0' } it { expect(video.content_detail).to be_a Yt::ContentDetail } it 'returns valid metadata' do expect(video.title).to be_a String expect(video.description).to be_a String expect(video.thumbnail_url).to be_a String expect(video.published_at).to be_a Time expect(video.privacy_status).to be_a String expect(video.tags).to be_an Array expect(video.channel_id).to be_a String expect(video.channel_title).to be_a String expect(video.channel_url).to be_a String expect(video.category_id).to be_a String expect(video.live_broadcast_content).to be_a String expect(video.view_count).to be_an Integer expect(video.like_count).to be_an Integer expect(video.dislike_count).to be_an Integer expect(video.favorite_count).to be_an Integer expect(video.comment_count).to be_an Integer expect(video.duration).to be_an Integer expect(video.hd?).to be_in [true, false] expect(video.stereoscopic?).to be_in [true, false] expect(video.captioned?).to be_in [true, false] expect(video.licensed?).to be_in [true, false] expect(video.deleted?).to be_in [true, false] expect(video.failed?).to be_in [true, false] expect(video.processed?).to be_in [true, false] expect(video.rejected?).to be_in [true, false] expect(video.uploading?).to be_in [true, false] expect(video.uses_unsupported_codec?).to be_in [true, false] expect(video.has_failed_conversion?).to be_in [true, false] expect(video.empty?).to be_in [true, false] expect(video.invalid?).to be_in [true, false] expect(video.too_small?).to be_in [true, false] expect(video.aborted?).to be_in [true, false] expect(video.claimed?).to be_in [true, false] expect(video.infringes_copyright?).to be_in [true, false] expect(video.duplicate?).to be_in [true, false] expect(video.scheduled_at.class).to be_in [NilClass, Time] expect(video.scheduled?).to be_in [true, false] expect(video.too_long?).to be_in [true, false] expect(video.violates_terms_of_use?).to be_in [true, false] expect(video.inappropriate?).to be_in [true, false] expect(video.infringes_trademark?).to be_in [true, false] expect(video.belongs_to_closed_account?).to be_in [true, false] expect(video.belongs_to_suspended_account?).to be_in [true, false] expect(video.licensed_as_creative_commons?).to be_in [true, false] expect(video.licensed_as_standard_youtube?).to be_in [true, false] expect(video.has_public_stats_viewable?).to be_in [true, false] expect(video.embeddable?).to be_in [true, false] expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_nil expect(video.scheduled_end_time).to be_nil expect(video.concurrent_viewers).to be_nil expect(video.embed_html).to be_a String expect(video.category_title).to be_a String end it { expect{video.update}.to fail } it { expect{video.delete}.to fail.with 'forbidden' } context 'that I like' do before { video.like } it { expect(video).to be_liked } it { expect(video.dislike).to be true } end context 'that I dislike' do before { video.dislike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end context 'that I am indifferent to' do before { video.unlike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end end context 'given someone else’s live video broadcast scheduled in the future' do let(:id) { 'PqzGI8gO_gk' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_nil end end context 'given someone else’s past live video broadcast' do let(:id) { 'COOM8_tOy6U' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_a Time expect(video.actual_end_time).to be_a Time expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_a Time expect(video.concurrent_viewers).to be_nil end end context 'given an unknown video' do let(:id) { 'not-a-video-id' } it { expect{video.content_detail}.to raise_error Yt::Errors::NoItems } it { expect{video.snippet}.to raise_error Yt::Errors::NoItems } it { expect{video.rating}.to raise_error Yt::Errors::NoItems } it { expect{video.status}.to raise_error Yt::Errors::NoItems } it { expect{video.statistics_set}.to raise_error Yt::Errors::NoItems } it { expect{video.file_detail}.to raise_error Yt::Errors::NoItems } end context 'given one of my own videos that I want to delete' do before(:all) { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: "Yt Test Delete Video #{rand}" } let(:id) { @tmp_video.id } it { expect(video.delete).to be true } end context 'given one of my own videos that I want to update' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let!(:old_title) { video.title } let!(:old_privacy_status) { video.privacy_status } let(:update) { video.update attrs } context 'given I update the title' do # NOTE: The use of UTF-8 characters is to test that we can pass up to # 50 characters, independently of their representation let(:attrs) { {title: "Yt Example Update Video #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the title' do expect(update).to be true expect(video.title).not_to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the description' do let!(:old_description) { video.description } let(:attrs) { {description: "Yt Example Description #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the description' do expect(update).to be true expect(video.description).not_to eq old_description expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the tags' do let!(:old_tags) { video.tags } let(:attrs) { {tags: ["Yt Test Tag #{rand}"]} } specify 'only updates the tag' do expect(update).to be true expect(video.tags).not_to eq old_tags expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the category ID' do let!(:old_category_id) { video.category_id } let!(:new_category_id) { old_category_id == '22' ? '21' : '22' } context 'passing the parameter in underscore syntax' do let(:attrs) { {category_id: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {categoryId: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id end end end context 'given I update title, description and/or tags using angle brackets' do let(:attrs) { {title: "Example Yt Test < >", description: '< >', tags: ['<tag>']} } specify 'updates them replacing angle brackets with similar unicode characters accepted by YouTube' do expect(update).to be true expect(video.title).to eq 'Example Yt Test ‹ ›' expect(video.description).to eq '‹ ›' expect(video.tags).to eq ['‹tag›'] end end # note: 'scheduled' videos cannot be set to 'unlisted' context 'given I update the privacy status' do before { video.update publish_at: nil if video.scheduled? } let!(:new_privacy_status) { old_privacy_status == 'private' ? 'unlisted' : 'private' } context 'passing the parameter in underscore syntax' do let(:attrs) { {privacy_status: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {privacyStatus: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end end context 'given I update the embeddable status' do let!(:old_embeddable) { video.embeddable? } let!(:new_embeddable) { !old_embeddable } let(:attrs) { {embeddable: new_embeddable} } # @note: This test is a reflection of another irrational behavior of # YouTube API. Although 'embeddable' can be passed as an 'update' # attribute according to the documentation, it simply does not work. # The day YouTube fixes it, then this test will finally fail and will # be removed, documenting how to update 'embeddable' too. # @see https://developers.google.com/youtube/v3/docs/videos/update # @see https://code.google.com/p/gdata-issues/issues/detail?id=4861 specify 'does not update the embeddable status' do expect(update).to be true expect(video.embeddable?).to eq old_embeddable end end context 'given I update the public stats viewable setting' do let!(:old_public_stats_viewable) { video.has_public_stats_viewable? } let!(:new_public_stats_viewable) { !old_public_stats_viewable } context 'passing the parameter in underscore syntax' do let(:attrs) { {public_stats_viewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publicStatsViewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end it 'returns valid reports for video-related metrics' do # Some reports are only available to Content Owners. # See content owner test for more details about what the methods return. expect{video.views}.not_to raise_error expect{video.comments}.not_to raise_error expect{video.likes}.not_to raise_error expect{video.dislikes}.not_to raise_error expect{video.shares}.not_to raise_error expect{video.subscribers_gained}.not_to raise_error expect{video.subscribers_lost}.not_to raise_error expect{video.videos_added_to_playlists}.not_to raise_error expect{video.videos_removed_from_playlists}.not_to raise_error expect{video.estimated_minutes_watched}.not_to raise_error expect{video.average_view_duration}.not_to raise_error expect{video.average_view_percentage}.not_to raise_error expect{video.annotation_clicks}.not_to raise_error expect{video.annotation_click_through_rate}.not_to raise_error expect{video.annotation_close_rate}.not_to raise_error expect{video.card_impressions}.not_to raise_error expect{video.card_clicks}.not_to raise_error expect{video.card_click_rate}.not_to raise_error expect{video.card_teaser_impressions}.not_to raise_error expect{video.card_teaser_clicks}.not_to raise_error expect{video.card_teaser_click_rate}.not_to raise_error expect{video.viewer_percentage}.not_to raise_error expect{video.estimated_revenue}.to raise_error Yt::Errors::Unauthorized expect{video.ad_impressions}.to raise_error Yt::Errors::Unauthorized expect{video.monetized_playbacks}.to raise_error Yt::Errors::Unauthorized expect{video.playback_based_cpm}.to raise_error Yt::Errors::Unauthorized expect{video.advertising_options_set}.to raise_error Yt::Errors::Forbidden end end # @note: This test is separated from the block above because, for some # undocumented reasons, if an existing video was private, then set to # unlisted, then set to private again, YouTube _sometimes_ raises a # 400 Error when trying to set the publishAt timestamp. # Therefore, just to test the updating of publishAt, we use a brand new # video (set to private), rather than reusing an existing one as above. context 'given one of my own *private* videos that I want to update' do before { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: old_title, privacy_status: old_privacy_status } let(:id) { @tmp_video.id } let!(:old_title) { "Yt Test Update publishAt Video #{rand}" } let!(:old_privacy_status) { 'private' } after { video.delete } let!(:new_scheduled_at) { Yt::Timestamp.parse("#{rand(30) + 1} Jan 2020", Time.now) } context 'passing the parameter in underscore syntax' do let(:attrs) { {publish_at: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title # NOTE: This is another irrational behavior of YouTube API. In short, # the response of Video#update *does not* include the publishAt value # even if it exists. You need to call Video#list again to get it. video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to private has no effect: expect(video.update privacy_status: 'private').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to unlisted/public removes publishAt: expect(video.update privacy_status: 'unlisted').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to be_nil end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publishAt: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.scheduled_at).to eq new_scheduled_at expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end # @note: This should somehow test that the thumbnail *changes*. However, # YouTube does not change the URL of the thumbnail even though the content # changes. A full test would have to *download* the thumbnails before and # after, and compare the files. For now, not raising error is enough. # Eventually, change to `expect{update}.to change{video.thumbnail_url}` context 'given one of my own videos for which I want to upload a thumbnail' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let(:update) { video.upload_thumbnail path_or_url } context 'given the path to a local JPG image file' do let(:path_or_url) { File.expand_path '../thumbnail.jpg', __FILE__ } it { expect{update}.not_to raise_error } end context 'given the path to a remote PNG image file' do let(:path_or_url) { 'https://bit.ly/yt_thumbnail' } it { expect{update}.not_to raise_error } end context 'given an invalid URL' do let(:path_or_url) { 'this-is-not-a-url' } it { expect{update}.to raise_error Yt::Errors::RequestError } end end # @note: This test is separated from the block above because YouTube only # returns file details for *some videos*: "The fileDetails object will # only be returned if the processingDetails.fileAvailability property # has a value of available.". Therefore, just to test fileDetails, we use a # different video that (for some unknown reason) is marked as 'available'. # Also note that I was not able to find a single video returning fileName, # therefore video.file_name is not returned by Yt, until it can be tested. # @see https://developers.google.com/youtube/v3/docs/videos#processingDetails.fileDetailsAvailability context 'given one of my own *available* videos' do let(:id) { 'yCmaOvUFhlI' } it 'returns valid file details' do expect(video.file_size).to be_an Integer expect(video.file_type).to be_a String expect(video.container).to be_a String end end end # encoding: UTF-8 require 'spec_helper' require 'yt/models/video' describe Yt::Video, :device_app do subject(:video) { Yt::Video.new id: id, auth: $account } context 'given someone else’s video' do let(:id) { '9bZkp7q19f0' } it { expect(video.content_detail).to be_a Yt::ContentDetail } it 'returns valid metadata' do expect(video.title).to be_a String expect(video.description).to be_a String expect(video.thumbnail_url).to be_a String expect(video.published_at).to be_a Time expect(video.privacy_status).to be_a String expect(video.tags).to be_an Array expect(video.channel_id).to be_a String expect(video.channel_title).to be_a String expect(video.channel_url).to be_a String expect(video.category_id).to be_a String expect(video.live_broadcast_content).to be_a String expect(video.view_count).to be_an Integer expect(video.like_count).to be_an Integer expect(video.dislike_count).to be_an Integer expect(video.favorite_count).to be_an Integer expect(video.comment_count).to be_an Integer expect(video.duration).to be_an Integer expect(video.hd?).to be_in [true, false] expect(video.stereoscopic?).to be_in [true, false] expect(video.captioned?).to be_in [true, false] expect(video.licensed?).to be_in [true, false] expect(video.deleted?).to be_in [true, false] expect(video.failed?).to be_in [true, false] expect(video.processed?).to be_in [true, false] expect(video.rejected?).to be_in [true, false] expect(video.uploading?).to be_in [true, false] expect(video.uses_unsupported_codec?).to be_in [true, false] expect(video.has_failed_conversion?).to be_in [true, false] expect(video.empty?).to be_in [true, false] expect(video.invalid?).to be_in [true, false] expect(video.too_small?).to be_in [true, false] expect(video.aborted?).to be_in [true, false] expect(video.claimed?).to be_in [true, false] expect(video.infringes_copyright?).to be_in [true, false] expect(video.duplicate?).to be_in [true, false] expect(video.scheduled_at.class).to be_in [NilClass, Time] expect(video.scheduled?).to be_in [true, false] expect(video.too_long?).to be_in [true, false] expect(video.violates_terms_of_use?).to be_in [true, false] expect(video.inappropriate?).to be_in [true, false] expect(video.infringes_trademark?).to be_in [true, false] expect(video.belongs_to_closed_account?).to be_in [true, false] expect(video.belongs_to_suspended_account?).to be_in [true, false] expect(video.licensed_as_creative_commons?).to be_in [true, false] expect(video.licensed_as_standard_youtube?).to be_in [true, false] expect(video.has_public_stats_viewable?).to be_in [true, false] expect(video.embeddable?).to be_in [true, false] expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_nil expect(video.scheduled_end_time).to be_nil expect(video.concurrent_viewers).to be_nil expect(video.embed_html).to be_a String expect(video.category_title).to be_a String end it { expect{video.update}.to fail } it { expect{video.delete}.to fail.with 'forbidden' } context 'that I like' do before { video.like } it { expect(video).to be_liked } it { expect(video.dislike).to be true } end context 'that I dislike' do before { video.dislike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end context 'that I am indifferent to' do before { video.unlike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end end context 'given someone else’s live video broadcast scheduled in the future' do let(:id) { 'PqzGI8gO_gk' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_nil end end context 'given someone else’s past live video broadcast' do let(:id) { 'COOM8_tOy6U' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_a Time expect(video.actual_end_time).to be_a Time expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_a Time expect(video.concurrent_viewers).to be_nil end end context 'given an unknown video' do let(:id) { 'not-a-video-id' } it { expect{video.content_detail}.to raise_error Yt::Errors::NoItems } it { expect{video.snippet}.to raise_error Yt::Errors::NoItems } it { expect{video.rating}.to raise_error Yt::Errors::NoItems } it { expect{video.status}.to raise_error Yt::Errors::NoItems } it { expect{video.statistics_set}.to raise_error Yt::Errors::NoItems } it { expect{video.file_detail}.to raise_error Yt::Errors::NoItems } end context 'given one of my own videos that I want to delete' do before(:all) { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: "Yt Test Delete Video #{rand}" } let(:id) { @tmp_video.id } it { expect(video.delete).to be true } end context 'given one of my own videos that I want to update' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let!(:old_title) { video.title } let!(:old_privacy_status) { video.privacy_status } let(:update) { video.update attrs } context 'given I update the title' do # NOTE: The use of UTF-8 characters is to test that we can pass up to # 50 characters, independently of their representation let(:attrs) { {title: "Yt Example Update Video #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the title' do expect(update).to be true expect(video.title).not_to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the description' do let!(:old_description) { video.description } let(:attrs) { {description: "Yt Example Description #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the description' do expect(update).to be true expect(video.description).not_to eq old_description expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the tags' do let!(:old_tags) { video.tags } let(:attrs) { {tags: ["Yt Test Tag #{rand}"]} } specify 'only updates the tag' do expect(update).to be true expect(video.tags).not_to eq old_tags expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the category ID' do let!(:old_category_id) { video.category_id } let!(:new_category_id) { old_category_id == '22' ? '21' : '22' } context 'passing the parameter in underscore syntax' do let(:attrs) { {category_id: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {categoryId: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id end end end context 'given I update title, description and/or tags using angle brackets' do let(:attrs) { {title: "Example Yt Test < >", description: '< >', tags: ['<tag>']} } specify 'updates them replacing angle brackets with similar unicode characters accepted by YouTube' do expect(update).to be true expect(video.title).to eq 'Example Yt Test ‹ ›' expect(video.description).to eq '‹ ›' expect(video.tags).to eq ['‹tag›'] end end # note: 'scheduled' videos cannot be set to 'unlisted' context 'given I update the privacy status' do before { video.update publish_at: nil if video.scheduled? } let!(:new_privacy_status) { old_privacy_status == 'private' ? 'unlisted' : 'private' } context 'passing the parameter in underscore syntax' do let(:attrs) { {privacy_status: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {privacyStatus: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end end context 'given I update the embeddable status' do let!(:old_embeddable) { video.embeddable? } let!(:new_embeddable) { !old_embeddable } let(:attrs) { {embeddable: new_embeddable} } # @note: This test is a reflection of another irrational behavior of # YouTube API. Although 'embeddable' can be passed as an 'update' # attribute according to the documentation, it simply does not work. # The day YouTube fixes it, then this test will finally fail and will # be removed, documenting how to update 'embeddable' too. # @see https://developers.google.com/youtube/v3/docs/videos/update # @see https://code.google.com/p/gdata-issues/issues/detail?id=4861 specify 'does not update the embeddable status' do expect(update).to be true expect(video.embeddable?).to eq old_embeddable end end context 'given I update the public stats viewable setting' do let!(:old_public_stats_viewable) { video.has_public_stats_viewable? } let!(:new_public_stats_viewable) { !old_public_stats_viewable } context 'passing the parameter in underscore syntax' do let(:attrs) { {public_stats_viewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publicStatsViewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end it 'returns valid reports for video-related metrics' do # Some reports are only available to Content Owners. # See content owner test for more details about what the methods return. expect{video.views}.not_to raise_error expect{video.comments}.not_to raise_error expect{video.likes}.not_to raise_error expect{video.dislikes}.not_to raise_error expect{video.shares}.not_to raise_error expect{video.subscribers_gained}.not_to raise_error expect{video.subscribers_lost}.not_to raise_error expect{video.videos_added_to_playlists}.not_to raise_error expect{video.videos_removed_from_playlists}.not_to raise_error expect{video.estimated_minutes_watched}.not_to raise_error expect{video.average_view_duration}.not_to raise_error expect{video.average_view_percentage}.not_to raise_error expect{video.annotation_clicks}.not_to raise_error expect{video.annotation_click_through_rate}.not_to raise_error expect{video.annotation_close_rate}.not_to raise_error expect{video.viewer_percentage}.not_to raise_error expect{video.estimated_revenue}.to raise_error Yt::Errors::Unauthorized expect{video.ad_impressions}.to raise_error Yt::Errors::Unauthorized expect{video.monetized_playbacks}.to raise_error Yt::Errors::Unauthorized expect{video.playback_based_cpm}.to raise_error Yt::Errors::Unauthorized expect{video.advertising_options_set}.to raise_error Yt::Errors::Forbidden end end # @note: This test is separated from the block above because, for some # undocumented reasons, if an existing video was private, then set to # unlisted, then set to private again, YouTube _sometimes_ raises a # 400 Error when trying to set the publishAt timestamp. # Therefore, just to test the updating of publishAt, we use a brand new # video (set to private), rather than reusing an existing one as above. context 'given one of my own *private* videos that I want to update' do before { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: old_title, privacy_status: old_privacy_status } let(:id) { @tmp_video.id } let!(:old_title) { "Yt Test Update publishAt Video #{rand}" } let!(:old_privacy_status) { 'private' } after { video.delete } let!(:new_scheduled_at) { Yt::Timestamp.parse("#{rand(30) + 1} Jan 2020", Time.now) } context 'passing the parameter in underscore syntax' do let(:attrs) { {publish_at: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title # NOTE: This is another irrational behavior of YouTube API. In short, # the response of Video#update *does not* include the publishAt value # even if it exists. You need to call Video#list again to get it. video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to private has no effect: expect(video.update privacy_status: 'private').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to unlisted/public removes publishAt: expect(video.update privacy_status: 'unlisted').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to be_nil end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publishAt: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.scheduled_at).to eq new_scheduled_at expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end # @note: This should somehow test that the thumbnail *changes*. However, # YouTube does not change the URL of the thumbnail even though the content # changes. A full test would have to *download* the thumbnails before and # after, and compare the files. For now, not raising error is enough. # Eventually, change to `expect{update}.to change{video.thumbnail_url}` context 'given one of my own videos for which I want to upload a thumbnail' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let(:update) { video.upload_thumbnail path_or_url } context 'given the path to a local JPG image file' do let(:path_or_url) { File.expand_path '../thumbnail.jpg', __FILE__ } it { expect{update}.not_to raise_error } end context 'given the path to a remote PNG image file' do let(:path_or_url) { 'https://bit.ly/yt_thumbnail' } it { expect{update}.not_to raise_error } end context 'given an invalid URL' do let(:path_or_url) { 'this-is-not-a-url' } it { expect{update}.to raise_error Yt::Errors::RequestError } end end # @note: This test is separated from the block above because YouTube only # returns file details for *some videos*: "The fileDetails object will # only be returned if the processingDetails.fileAvailability property # has a value of available.". Therefore, just to test fileDetails, we use a # different video that (for some unknown reason) is marked as 'available'. # Also note that I was not able to find a single video returning fileName, # therefore video.file_name is not returned by Yt, until it can be tested. # @see https://developers.google.com/youtube/v3/docs/videos#processingDetails.fileDetailsAvailability context 'given one of my own *available* videos' do let(:id) { 'yCmaOvUFhlI' } it 'returns valid file details' do expect(video.file_size).to be_an Integer expect(video.file_type).to be_a String expect(video.container).to be_a String end end end # encoding: UTF-8 require 'spec_helper' require 'yt/models/video' describe Yt::Video, :device_app do subject(:video) { Yt::Video.new id: id, auth: $account } context 'given someone else’s video' do let(:id) { '9bZkp7q19f0' } it { expect(video.content_detail).to be_a Yt::ContentDetail } it 'returns valid metadata' do expect(video.title).to be_a String expect(video.description).to be_a String expect(video.thumbnail_url).to be_a String expect(video.published_at).to be_a Time expect(video.privacy_status).to be_a String expect(video.tags).to be_an Array expect(video.channel_id).to be_a String expect(video.channel_title).to be_a String expect(video.channel_url).to be_a String expect(video.category_id).to be_a String expect(video.live_broadcast_content).to be_a String expect(video.view_count).to be_an Integer expect(video.like_count).to be_an Integer expect(video.dislike_count).to be_an Integer expect(video.favorite_count).to be_an Integer expect(video.comment_count).to be_an Integer expect(video.duration).to be_an Integer expect(video.hd?).to be_in [true, false] expect(video.stereoscopic?).to be_in [true, false] expect(video.captioned?).to be_in [true, false] expect(video.licensed?).to be_in [true, false] expect(video.deleted?).to be_in [true, false] expect(video.failed?).to be_in [true, false] expect(video.processed?).to be_in [true, false] expect(video.rejected?).to be_in [true, false] expect(video.uploading?).to be_in [true, false] expect(video.uses_unsupported_codec?).to be_in [true, false] expect(video.has_failed_conversion?).to be_in [true, false] expect(video.empty?).to be_in [true, false] expect(video.invalid?).to be_in [true, false] expect(video.too_small?).to be_in [true, false] expect(video.aborted?).to be_in [true, false] expect(video.claimed?).to be_in [true, false] expect(video.infringes_copyright?).to be_in [true, false] expect(video.duplicate?).to be_in [true, false] expect(video.scheduled_at.class).to be_in [NilClass, Time] expect(video.scheduled?).to be_in [true, false] expect(video.too_long?).to be_in [true, false] expect(video.violates_terms_of_use?).to be_in [true, false] expect(video.inappropriate?).to be_in [true, false] expect(video.infringes_trademark?).to be_in [true, false] expect(video.belongs_to_closed_account?).to be_in [true, false] expect(video.belongs_to_suspended_account?).to be_in [true, false] expect(video.licensed_as_creative_commons?).to be_in [true, false] expect(video.licensed_as_standard_youtube?).to be_in [true, false] expect(video.has_public_stats_viewable?).to be_in [true, false] expect(video.embeddable?).to be_in [true, false] expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_nil expect(video.scheduled_end_time).to be_nil expect(video.concurrent_viewers).to be_nil expect(video.embed_html).to be_a String expect(video.category_title).to be_a String end it { expect{video.update}.to fail } it { expect{video.delete}.to fail.with 'forbidden' } context 'that I like' do before { video.like } it { expect(video).to be_liked } it { expect(video.dislike).to be true } end context 'that I dislike' do before { video.dislike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end context 'that I am indifferent to' do before { video.unlike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end end context 'given someone else’s live video broadcast scheduled in the future' do let(:id) { 'PqzGI8gO_gk' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_nil end end context 'given someone else’s past live video broadcast' do let(:id) { 'COOM8_tOy6U' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_a Time expect(video.actual_end_time).to be_a Time expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_a Time expect(video.concurrent_viewers).to be_nil end end context 'given an unknown video' do let(:id) { 'not-a-video-id' } it { expect{video.content_detail}.to raise_error Yt::Errors::NoItems } it { expect{video.snippet}.to raise_error Yt::Errors::NoItems } it { expect{video.rating}.to raise_error Yt::Errors::NoItems } it { expect{video.status}.to raise_error Yt::Errors::NoItems } it { expect{video.statistics_set}.to raise_error Yt::Errors::NoItems } it { expect{video.file_detail}.to raise_error Yt::Errors::NoItems } end context 'given one of my own videos that I want to delete' do before(:all) { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: "Yt Test Delete Video #{rand}" } let(:id) { @tmp_video.id } it { expect(video.delete).to be true } end context 'given one of my own videos that I want to update' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let!(:old_title) { video.title } let!(:old_privacy_status) { video.privacy_status } let(:update) { video.update attrs } context 'given I update the title' do # NOTE: The use of UTF-8 characters is to test that we can pass up to # 50 characters, independently of their representation let(:attrs) { {title: "Yt Example Update Video #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the title' do expect(update).to be true expect(video.title).not_to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the description' do let!(:old_description) { video.description } let(:attrs) { {description: "Yt Example Description #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the description' do expect(update).to be true expect(video.description).not_to eq old_description expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the tags' do let!(:old_tags) { video.tags } let(:attrs) { {tags: ["Yt Test Tag #{rand}"]} } specify 'only updates the tag' do expect(update).to be true expect(video.tags).not_to eq old_tags expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the category ID' do let!(:old_category_id) { video.category_id } let!(:new_category_id) { old_category_id == '22' ? '21' : '22' } context 'passing the parameter in underscore syntax' do let(:attrs) { {category_id: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {categoryId: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id end end end context 'given I update title, description and/or tags using angle brackets' do let(:attrs) { {title: "Example Yt Test < >", description: '< >', tags: ['<tag>']} } specify 'updates them replacing angle brackets with similar unicode characters accepted by YouTube' do expect(update).to be true expect(video.title).to eq 'Example Yt Test ‹ ›' expect(video.description).to eq '‹ ›' expect(video.tags).to eq ['‹tag›'] end end # note: 'scheduled' videos cannot be set to 'unlisted' context 'given I update the privacy status' do before { video.update publish_at: nil if video.scheduled? } let!(:new_privacy_status) { old_privacy_status == 'private' ? 'unlisted' : 'private' } context 'passing the parameter in underscore syntax' do let(:attrs) { {privacy_status: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {privacyStatus: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end end context 'given I update the public stats viewable setting' do let!(:old_public_stats_viewable) { video.has_public_stats_viewable? } let!(:new_public_stats_viewable) { !old_public_stats_viewable } context 'passing the parameter in underscore syntax' do let(:attrs) { {public_stats_viewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publicStatsViewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end it 'returns valid reports for video-related metrics' do # Some reports are only available to Content Owners. # See content owner test for more details about what the methods return. expect{video.views}.not_to raise_error expect{video.comments}.not_to raise_error expect{video.likes}.not_to raise_error expect{video.dislikes}.not_to raise_error expect{video.shares}.not_to raise_error expect{video.subscribers_gained}.not_to raise_error expect{video.subscribers_lost}.not_to raise_error expect{video.videos_added_to_playlists}.not_to raise_error expect{video.videos_removed_from_playlists}.not_to raise_error expect{video.estimated_minutes_watched}.not_to raise_error expect{video.average_view_duration}.not_to raise_error expect{video.average_view_percentage}.not_to raise_error expect{video.annotation_clicks}.not_to raise_error expect{video.annotation_click_through_rate}.not_to raise_error expect{video.annotation_close_rate}.not_to raise_error expect{video.viewer_percentage}.not_to raise_error expect{video.estimated_revenue}.to raise_error Yt::Errors::Unauthorized expect{video.ad_impressions}.to raise_error Yt::Errors::Unauthorized expect{video.monetized_playbacks}.to raise_error Yt::Errors::Unauthorized expect{video.playback_based_cpm}.to raise_error Yt::Errors::Unauthorized expect{video.advertising_options_set}.to raise_error Yt::Errors::Forbidden end end # @note: This test is separated from the block above because, for some # undocumented reasons, if an existing video was private, then set to # unlisted, then set to private again, YouTube _sometimes_ raises a # 400 Error when trying to set the publishAt timestamp. # Therefore, just to test the updating of publishAt, we use a brand new # video (set to private), rather than reusing an existing one as above. context 'given one of my own *private* videos that I want to update' do before { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: old_title, privacy_status: old_privacy_status } let(:id) { @tmp_video.id } let!(:old_title) { "Yt Test Update publishAt Video #{rand}" } let!(:old_privacy_status) { 'private' } after { video.delete } let!(:new_scheduled_at) { Yt::Timestamp.parse("#{rand(30) + 1} Jan 2020", Time.now) } context 'passing the parameter in underscore syntax' do let(:attrs) { {publish_at: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title # NOTE: This is another irrational behavior of YouTube API. In short, # the response of Video#update *does not* include the publishAt value # even if it exists. You need to call Video#list again to get it. video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to private has no effect: expect(video.update privacy_status: 'private').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to unlisted/public removes publishAt: expect(video.update privacy_status: 'unlisted').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to be_nil end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publishAt: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.scheduled_at).to eq new_scheduled_at expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end # @note: This should somehow test that the thumbnail *changes*. However, # YouTube does not change the URL of the thumbnail even though the content # changes. A full test would have to *download* the thumbnails before and # after, and compare the files. For now, not raising error is enough. # Eventually, change to `expect{update}.to change{video.thumbnail_url}` context 'given one of my own videos for which I want to upload a thumbnail' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let(:update) { video.upload_thumbnail path_or_url } context 'given the path to a local JPG image file' do let(:path_or_url) { File.expand_path '../thumbnail.jpg', __FILE__ } it { expect{update}.not_to raise_error } end context 'given the path to a remote PNG image file' do let(:path_or_url) { 'https://bit.ly/yt_thumbnail' } it { expect{update}.not_to raise_error } end context 'given an invalid URL' do let(:path_or_url) { 'this-is-not-a-url' } it { expect{update}.to raise_error Yt::Errors::RequestError } end end # @note: This test is separated from the block above because YouTube only # returns file details for *some videos*: "The fileDetails object will # only be returned if the processingDetails.fileAvailability property # has a value of available.". Therefore, just to test fileDetails, we use a # different video that (for some unknown reason) is marked as 'available'. # Also note that I was not able to find a single video returning fileName, # therefore video.file_name is not returned by Yt, until it can be tested. # @see https://developers.google.com/youtube/v3/docs/videos#processingDetails.fileDetailsAvailability context 'given one of my own *available* videos' do let(:id) { 'yCmaOvUFhlI' } it 'returns valid file details' do expect(video.file_size).to be_an Integer expect(video.file_type).to be_a String expect(video.container).to be_a String end end end # encoding: UTF-8 require 'spec_helper' require 'yt/models/video' describe Yt::Video, :device_app do subject(:video) { Yt::Video.new id: id, auth: $account } context 'given someone else’s video' do let(:id) { '9bZkp7q19f0' } it { expect(video.content_detail).to be_a Yt::ContentDetail } it 'returns valid metadata' do expect(video.title).to be_a String expect(video.description).to be_a String expect(video.thumbnail_url).to be_a String expect(video.published_at).to be_a Time expect(video.privacy_status).to be_a String expect(video.tags).to be_an Array expect(video.channel_id).to be_a String expect(video.channel_title).to be_a String expect(video.channel_url).to be_a String expect(video.category_id).to be_a String expect(video.live_broadcast_content).to be_a String expect(video.view_count).to be_an Integer expect(video.like_count).to be_an Integer expect(video.dislike_count).to be_an Integer expect(video.favorite_count).to be_an Integer expect(video.comment_count).to be_an Integer expect(video.duration).to be_an Integer expect(video.hd?).to be_in [true, false] expect(video.stereoscopic?).to be_in [true, false] expect(video.captioned?).to be_in [true, false] expect(video.licensed?).to be_in [true, false] expect(video.deleted?).to be_in [true, false] expect(video.failed?).to be_in [true, false] expect(video.processed?).to be_in [true, false] expect(video.rejected?).to be_in [true, false] expect(video.uploading?).to be_in [true, false] expect(video.uses_unsupported_codec?).to be_in [true, false] expect(video.has_failed_conversion?).to be_in [true, false] expect(video.empty?).to be_in [true, false] expect(video.invalid?).to be_in [true, false] expect(video.too_small?).to be_in [true, false] expect(video.aborted?).to be_in [true, false] expect(video.claimed?).to be_in [true, false] expect(video.infringes_copyright?).to be_in [true, false] expect(video.duplicate?).to be_in [true, false] expect(video.scheduled_at.class).to be_in [NilClass, Time] expect(video.scheduled?).to be_in [true, false] expect(video.too_long?).to be_in [true, false] expect(video.violates_terms_of_use?).to be_in [true, false] expect(video.inappropriate?).to be_in [true, false] expect(video.infringes_trademark?).to be_in [true, false] expect(video.belongs_to_closed_account?).to be_in [true, false] expect(video.belongs_to_suspended_account?).to be_in [true, false] expect(video.licensed_as_creative_commons?).to be_in [true, false] expect(video.licensed_as_standard_youtube?).to be_in [true, false] expect(video.has_public_stats_viewable?).to be_in [true, false] expect(video.embeddable?).to be_in [true, false] expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_nil expect(video.scheduled_end_time).to be_nil expect(video.concurrent_viewers).to be_nil expect(video.embed_html).to be_a String expect(video.category_title).to be_a String end it { expect{video.update}.to fail } it { expect{video.delete}.to fail.with 'forbidden' } context 'that I like' do before { video.like } it { expect(video).to be_liked } it { expect(video.dislike).to be true } end context 'that I dislike' do before { video.dislike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end context 'that I am indifferent to' do before { video.unlike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end end context 'given someone else’s live video broadcast scheduled in the future' do let(:id) { 'PqzGI8gO_gk' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_nil end end context 'given someone else’s past live video broadcast' do let(:id) { 'COOM8_tOy6U' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_a Time expect(video.actual_end_time).to be_a Time expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_a Time expect(video.concurrent_viewers).to be_nil end end context 'given an unknown video' do let(:id) { 'not-a-video-id' } it { expect{video.content_detail}.to raise_error Yt::Errors::NoItems } it { expect{video.snippet}.to raise_error Yt::Errors::NoItems } it { expect{video.rating}.to raise_error Yt::Errors::NoItems } it { expect{video.status}.to raise_error Yt::Errors::NoItems } it { expect{video.statistics_set}.to raise_error Yt::Errors::NoItems } it { expect{video.file_detail}.to raise_error Yt::Errors::NoItems } end context 'given one of my own videos that I want to delete' do before(:all) { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: "Yt Test Delete Video #{rand}" } let(:id) { @tmp_video.id } it { expect(video.delete).to be true } end context 'given one of my own videos that I want to update' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let!(:old_title) { video.title } let!(:old_privacy_status) { video.privacy_status } let(:update) { video.update attrs } context 'given I update the title' do # NOTE: The use of UTF-8 characters is to test that we can pass up to # 50 characters, independently of their representation let(:attrs) { {title: "Yt Example Update Video #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the title' do expect(update).to be true expect(video.title).not_to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the description' do let!(:old_description) { video.description } let(:attrs) { {description: "Yt Example Description #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the description' do expect(update).to be true expect(video.description).not_to eq old_description expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the tags' do let!(:old_tags) { video.tags } let(:attrs) { {tags: ["Yt Test Tag #{rand}"]} } specify 'only updates the tag' do expect(update).to be true expect(video.tags).not_to eq old_tags expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the category ID' do let!(:old_category_id) { video.category_id } let!(:new_category_id) { old_category_id == '22' ? '21' : '22' } context 'passing the parameter in underscore syntax' do let(:attrs) { {category_id: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {categoryId: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id end end end context 'given I update title, description and/or tags using angle brackets' do let(:attrs) { {title: "Example Yt Test < >", description: '< >', tags: ['<tag>']} } specify 'updates them replacing angle brackets with similar unicode characters accepted by YouTube' do expect(update).to be true expect(video.title).to eq 'Example Yt Test ‹ ›' expect(video.description).to eq '‹ ›' expect(video.tags).to eq ['‹tag›'] end end # note: 'scheduled' videos cannot be set to 'unlisted' context 'given I update the privacy status' do before { video.update publish_at: nil if video.scheduled? } let!(:new_privacy_status) { old_privacy_status == 'private' ? 'unlisted' : 'private' } context 'passing the parameter in underscore syntax' do let(:attrs) { {privacy_status: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {privacyStatus: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end end context 'given I update the embeddable status' do let!(:old_embeddable) { video.embeddable? } let!(:new_embeddable) { !old_embeddable } let(:attrs) { {embeddable: new_embeddable} } # @note: This test is a reflection of another irrational behavior of # YouTube API. Although 'embeddable' can be passed as an 'update' # attribute according to the documentation, it simply does not work. # The day YouTube fixes it, then this test will finally fail and will # be removed, documenting how to update 'embeddable' too. # @see https://developers.google.com/youtube/v3/docs/videos/update # @see https://code.google.com/p/gdata-issues/issues/detail?id=4861 specify 'does not update the embeddable status' do expect(update).to be true expect(video.embeddable?).to eq old_embeddable end end context 'given I update the public stats viewable setting' do let!(:old_public_stats_viewable) { video.has_public_stats_viewable? } let!(:new_public_stats_viewable) { !old_public_stats_viewable } context 'passing the parameter in underscore syntax' do let(:attrs) { {public_stats_viewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publicStatsViewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end it 'returns valid reports for video-related metrics' do # Some reports are only available to Content Owners. # See content owner test for more details about what the methods return. expect{video.views}.not_to raise_error expect{video.comments}.not_to raise_error expect{video.likes}.not_to raise_error expect{video.dislikes}.not_to raise_error expect{video.shares}.not_to raise_error expect{video.subscribers_gained}.not_to raise_error expect{video.subscribers_lost}.not_to raise_error expect{video.videos_added_to_playlists}.not_to raise_error expect{video.videos_removed_from_playlists}.not_to raise_error expect{video.estimated_minutes_watched}.not_to raise_error expect{video.average_view_duration}.not_to raise_error expect{video.average_view_percentage}.not_to raise_error expect{video.annotation_clicks}.not_to raise_error expect{video.annotation_click_through_rate}.not_to raise_error expect{video.annotation_close_rate}.not_to raise_error expect{video.viewer_percentage}.not_to raise_error expect{video.estimated_revenue}.to raise_error Yt::Errors::Unauthorized expect{video.ad_impressions}.to raise_error Yt::Errors::Unauthorized expect{video.monetized_playbacks}.to raise_error Yt::Errors::Unauthorized expect{video.playback_based_cpm}.to raise_error Yt::Errors::Unauthorized expect{video.advertising_options_set}.to raise_error Yt::Errors::Forbidden end end # @note: This test is separated from the block above because, for some # undocumented reasons, if an existing video was private, then set to # unlisted, then set to private again, YouTube _sometimes_ raises a # 400 Error when trying to set the publishAt timestamp. # Therefore, just to test the updating of publishAt, we use a brand new # video (set to private), rather than reusing an existing one as above. context 'given one of my own *private* videos that I want to update' do before { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: old_title, privacy_status: old_privacy_status } let(:id) { @tmp_video.id } let!(:old_title) { "Yt Test Update publishAt Video #{rand}" } let!(:old_privacy_status) { 'private' } after { video.delete } let!(:new_scheduled_at) { Yt::Timestamp.parse("#{rand(30) + 1} Jan 2020", Time.now) } context 'passing the parameter in underscore syntax' do let(:attrs) { {publish_at: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title # NOTE: This is another irrational behavior of YouTube API. In short, # the response of Video#update *does not* include the publishAt value # even if it exists. You need to call Video#list again to get it. video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to private has no effect: expect(video.update privacy_status: 'private').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to unlisted/public removes publishAt: expect(video.update privacy_status: 'unlisted').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to be_nil end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publishAt: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.scheduled_at).to eq new_scheduled_at expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end # @note: This should somehow test that the thumbnail *changes*. However, # YouTube does not change the URL of the thumbnail even though the content # changes. A full test would have to *download* the thumbnails before and # after, and compare the files. For now, not raising error is enough. # Eventually, change to `expect{update}.to change{video.thumbnail_url}` context 'given one of my own videos for which I want to upload a thumbnail' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let(:update) { video.upload_thumbnail path_or_url } context 'given the path to a local JPG image file' do let(:path_or_url) { File.expand_path '../thumbnail.jpg', __FILE__ } it { expect{update}.not_to raise_error } end context 'given the path to a remote PNG image file' do let(:path_or_url) { 'https://bit.ly/yt_thumbnail' } it { expect{update}.not_to raise_error } end context 'given an invalid URL' do let(:path_or_url) { 'this-is-not-a-url' } it { expect{update}.to raise_error Yt::Errors::RequestError } end end # @note: This test is separated from the block above because YouTube only # returns file details for *some videos*: "The fileDetails object will # only be returned if the processingDetails.fileAvailability property # has a value of available.". Therefore, just to test fileDetails, we use a # different video that (for some unknown reason) is marked as 'available'. # Also note that I was not able to find a single video returning fileName, # therefore video.file_name is not returned by Yt, until it can be tested. # @see https://developers.google.com/youtube/v3/docs/videos#processingDetails.fileDetailsAvailability context 'given one of my own *available* videos' do let(:id) { 'yCmaOvUFhlI' } it 'returns valid file details' do expect(video.file_size).to be_an Integer expect(video.file_type).to be_a String expect(video.container).to be_a String end end end # encoding: UTF-8 require 'spec_helper' require 'yt/models/video' describe Yt::Video, :device_app do subject(:video) { Yt::Video.new id: id, auth: $account } context 'given someone else’s video' do let(:id) { '9bZkp7q19f0' } it { expect(video.content_detail).to be_a Yt::ContentDetail } it 'returns valid metadata' do expect(video.title).to be_a String expect(video.description).to be_a String expect(video.thumbnail_url).to be_a String expect(video.published_at).to be_a Time expect(video.privacy_status).to be_a String expect(video.tags).to be_an Array expect(video.channel_id).to be_a String expect(video.channel_title).to be_a String expect(video.channel_url).to be_a String expect(video.category_id).to be_a String expect(video.live_broadcast_content).to be_a String expect(video.view_count).to be_an Integer expect(video.like_count).to be_an Integer expect(video.dislike_count).to be_an Integer expect(video.favorite_count).to be_an Integer expect(video.comment_count).to be_an Integer expect(video.duration).to be_an Integer expect(video.hd?).to be_in [true, false] expect(video.stereoscopic?).to be_in [true, false] expect(video.captioned?).to be_in [true, false] expect(video.licensed?).to be_in [true, false] expect(video.deleted?).to be_in [true, false] expect(video.failed?).to be_in [true, false] expect(video.processed?).to be_in [true, false] expect(video.rejected?).to be_in [true, false] expect(video.uploading?).to be_in [true, false] expect(video.uses_unsupported_codec?).to be_in [true, false] expect(video.has_failed_conversion?).to be_in [true, false] expect(video.empty?).to be_in [true, false] expect(video.invalid?).to be_in [true, false] expect(video.too_small?).to be_in [true, false] expect(video.aborted?).to be_in [true, false] expect(video.claimed?).to be_in [true, false] expect(video.infringes_copyright?).to be_in [true, false] expect(video.duplicate?).to be_in [true, false] expect(video.scheduled_at.class).to be_in [NilClass, Time] expect(video.scheduled?).to be_in [true, false] expect(video.too_long?).to be_in [true, false] expect(video.violates_terms_of_use?).to be_in [true, false] expect(video.inappropriate?).to be_in [true, false] expect(video.infringes_trademark?).to be_in [true, false] expect(video.belongs_to_closed_account?).to be_in [true, false] expect(video.belongs_to_suspended_account?).to be_in [true, false] expect(video.licensed_as_creative_commons?).to be_in [true, false] expect(video.licensed_as_standard_youtube?).to be_in [true, false] expect(video.has_public_stats_viewable?).to be_in [true, false] expect(video.embeddable?).to be_in [true, false] expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_nil expect(video.scheduled_end_time).to be_nil expect(video.concurrent_viewers).to be_nil expect(video.embed_html).to be_a String expect(video.category_title).to be_a String end it { expect{video.update}.to fail } it { expect{video.delete}.to fail.with 'forbidden' } context 'that I like' do before { video.like } it { expect(video).to be_liked } it { expect(video.dislike).to be true } end context 'that I dislike' do before { video.dislike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end context 'that I am indifferent to' do before { video.unlike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end end context 'given someone else’s live video broadcast scheduled in the future' do let(:id) { 'PqzGI8gO_gk' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_nil end end context 'given someone else’s past live video broadcast' do let(:id) { 'COOM8_tOy6U' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_a Time expect(video.actual_end_time).to be_a Time expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_a Time expect(video.concurrent_viewers).to be_nil end end context 'given an unknown video' do let(:id) { 'not-a-video-id' } it { expect{video.content_detail}.to raise_error Yt::Errors::NoItems } it { expect{video.snippet}.to raise_error Yt::Errors::NoItems } it { expect{video.rating}.to raise_error Yt::Errors::NoItems } it { expect{video.status}.to raise_error Yt::Errors::NoItems } it { expect{video.statistics_set}.to raise_error Yt::Errors::NoItems } it { expect{video.file_detail}.to raise_error Yt::Errors::NoItems } end context 'given one of my own videos that I want to delete' do before(:all) { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: "Yt Test Delete Video #{rand}" } let(:id) { @tmp_video.id } it { expect(video.delete).to be true } end context 'given one of my own videos that I want to update' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let!(:old_title) { video.title } let!(:old_privacy_status) { video.privacy_status } let(:update) { video.update attrs } context 'given I update the title' do # NOTE: The use of UTF-8 characters is to test that we can pass up to # 50 characters, independently of their representation let(:attrs) { {title: "Yt Example Update Video #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the title' do expect(update).to be true expect(video.title).not_to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the description' do let!(:old_description) { video.description } let(:attrs) { {description: "Yt Example Description #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the description' do expect(update).to be true expect(video.description).not_to eq old_description expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the tags' do let!(:old_tags) { video.tags } let(:attrs) { {tags: ["Yt Test Tag #{rand}"]} } specify 'only updates the tag' do expect(update).to be true expect(video.tags).not_to eq old_tags expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the category ID' do let!(:old_category_id) { video.category_id } let!(:new_category_id) { old_category_id == '22' ? '21' : '22' } context 'passing the parameter in underscore syntax' do let(:attrs) { {category_id: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {categoryId: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id end end end context 'given I update title, description and/or tags using angle brackets' do let(:attrs) { {title: "Example Yt Test < >", description: '< >', tags: ['<tag>']} } specify 'updates them replacing angle brackets with similar unicode characters accepted by YouTube' do expect(update).to be true expect(video.title).to eq 'Example Yt Test ‹ ›' expect(video.description).to eq '‹ ›' expect(video.tags).to eq ['‹tag›'] end end # note: 'scheduled' videos cannot be set to 'unlisted' context 'given I update the privacy status' do before { video.update publish_at: nil if video.scheduled? } let!(:new_privacy_status) { old_privacy_status == 'private' ? 'unlisted' : 'private' } context 'passing the parameter in underscore syntax' do let(:attrs) { {privacy_status: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {privacyStatus: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end end context 'given I update the embeddable status' do let!(:old_embeddable) { video.embeddable? } let!(:new_embeddable) { !old_embeddable } let(:attrs) { {embeddable: new_embeddable} } # @note: This test is a reflection of another irrational behavior of # YouTube API. Although 'embeddable' can be passed as an 'update' # attribute according to the documentation, it simply does not work. # The day YouTube fixes it, then this test will finally fail and will # be removed, documenting how to update 'embeddable' too. # @see https://developers.google.com/youtube/v3/docs/videos/update # @see https://code.google.com/p/gdata-issues/issues/detail?id=4861 specify 'does not update the embeddable status' do expect(update).to be true expect(video.embeddable?).to eq old_embeddable end end context 'given I update the public stats viewable setting' do let!(:old_public_stats_viewable) { video.has_public_stats_viewable? } let!(:new_public_stats_viewable) { !old_public_stats_viewable } context 'passing the parameter in underscore syntax' do let(:attrs) { {public_stats_viewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publicStatsViewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end it 'returns valid reports for video-related metrics' do # Some reports are only available to Content Owners. # See content owner test for more details about what the methods return. expect{video.views}.not_to raise_error expect{video.comments}.not_to raise_error expect{video.likes}.not_to raise_error expect{video.dislikes}.not_to raise_error expect{video.shares}.not_to raise_error expect{video.subscribers_gained}.not_to raise_error expect{video.subscribers_lost}.not_to raise_error expect{video.videos_added_to_playlists}.not_to raise_error expect{video.videos_removed_from_playlists}.not_to raise_error expect{video.estimated_minutes_watched}.not_to raise_error expect{video.average_view_duration}.not_to raise_error expect{video.average_view_percentage}.not_to raise_error expect{video.annotation_clicks}.not_to raise_error expect{video.annotation_click_through_rate}.not_to raise_error expect{video.annotation_close_rate}.not_to raise_error expect{video.viewer_percentage}.not_to raise_error expect{video.estimated_revenue}.to raise_error Yt::Errors::Unauthorized expect{video.ad_impressions}.to raise_error Yt::Errors::Unauthorized expect{video.monetized_playbacks}.to raise_error Yt::Errors::Unauthorized expect{video.playback_based_cpm}.to raise_error Yt::Errors::Unauthorized expect{video.advertising_options_set}.to raise_error Yt::Errors::Forbidden end end # @note: This test is separated from the block above because, for some # undocumented reasons, if an existing video was private, then set to # unlisted, then set to private again, YouTube _sometimes_ raises a # 400 Error when trying to set the publishAt timestamp. # Therefore, just to test the updating of publishAt, we use a brand new # video (set to private), rather than reusing an existing one as above. context 'given one of my own *private* videos that I want to update' do before { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: old_title, privacy_status: old_privacy_status } let(:id) { @tmp_video.id } let!(:old_title) { "Yt Test Update publishAt Video #{rand}" } let!(:old_privacy_status) { 'private' } after { video.delete } let!(:new_scheduled_at) { Yt::Timestamp.parse("#{rand(30) + 1} Jan 2020", Time.now) } context 'passing the parameter in underscore syntax' do let(:attrs) { {publish_at: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title # NOTE: This is another irrational behavior of YouTube API. In short, # the response of Video#update *does not* include the publishAt value # even if it exists. You need to call Video#list again to get it. video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to private has no effect: expect(video.update privacy_status: 'private').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to unlisted/public removes publishAt: expect(video.update privacy_status: 'unlisted').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to be_nil end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publishAt: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.scheduled_at).to eq new_scheduled_at expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end # @note: This should somehow test that the thumbnail *changes*. However, # YouTube does not change the URL of the thumbnail even though the content # changes. A full test would have to *download* the thumbnails before and # after, and compare the files. For now, not raising error is enough. # Eventually, change to `expect{update}.to change{video.thumbnail_url}` context 'given one of my own videos for which I want to upload a thumbnail' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let(:update) { video.upload_thumbnail path_or_url } context 'given the path to a local JPG image file' do let(:path_or_url) { File.expand_path '../thumbnail.jpg', __FILE__ } it { expect{update}.not_to raise_error } end context 'given the path to a remote PNG image file' do let(:path_or_url) { 'https://bit.ly/yt_thumbnail' } it { expect{update}.not_to raise_error } end context 'given an invalid URL' do let(:path_or_url) { 'this-is-not-a-url' } it { expect{update}.to raise_error Yt::Errors::RequestError } end end # @note: This test is separated from the block above because YouTube only # returns file details for *some videos*: "The fileDetails object will # only be returned if the processingDetails.fileAvailability property # has a value of available.". Therefore, just to test fileDetails, we use a # different video that (for some unknown reason) is marked as 'available'. # Also note that I was not able to find a single video returning fileName, # therefore video.file_name is not returned by Yt, until it can be tested. # @see https://developers.google.com/youtube/v3/docs/videos#processingDetails.fileDetailsAvailability context 'given one of my own *available* videos' do let(:id) { 'yCmaOvUFhlI' } it 'returns valid file details' do expect(video.file_size).to be_an Integer expect(video.file_type).to be_a String expect(video.container).to be_a String end end end # encoding: UTF-8 require 'spec_helper' require 'yt/models/video' describe Yt::Video, :device_app do subject(:video) { Yt::Video.new id: id, auth: $account } context 'given someone else’s video' do let(:id) { '9bZkp7q19f0' } it { expect(video.content_detail).to be_a Yt::ContentDetail } it 'returns valid metadata' do expect(video.title).to be_a String expect(video.description).to be_a String expect(video.thumbnail_url).to be_a String expect(video.published_at).to be_a Time expect(video.privacy_status).to be_a String expect(video.tags).to be_an Array expect(video.channel_id).to be_a String expect(video.channel_title).to be_a String expect(video.channel_url).to be_a String expect(video.category_id).to be_a String expect(video.live_broadcast_content).to be_a String expect(video.view_count).to be_an Integer expect(video.like_count).to be_an Integer expect(video.dislike_count).to be_an Integer expect(video.favorite_count).to be_an Integer expect(video.comment_count).to be_an Integer expect(video.duration).to be_an Integer expect(video.hd?).to be_in [true, false] expect(video.stereoscopic?).to be_in [true, false] expect(video.captioned?).to be_in [true, false] expect(video.licensed?).to be_in [true, false] expect(video.deleted?).to be_in [true, false] expect(video.failed?).to be_in [true, false] expect(video.processed?).to be_in [true, false] expect(video.rejected?).to be_in [true, false] expect(video.uploading?).to be_in [true, false] expect(video.uses_unsupported_codec?).to be_in [true, false] expect(video.has_failed_conversion?).to be_in [true, false] expect(video.empty?).to be_in [true, false] expect(video.invalid?).to be_in [true, false] expect(video.too_small?).to be_in [true, false] expect(video.aborted?).to be_in [true, false] expect(video.claimed?).to be_in [true, false] expect(video.infringes_copyright?).to be_in [true, false] expect(video.duplicate?).to be_in [true, false] expect(video.scheduled_at.class).to be_in [NilClass, Time] expect(video.scheduled?).to be_in [true, false] expect(video.too_long?).to be_in [true, false] expect(video.violates_terms_of_use?).to be_in [true, false] expect(video.inappropriate?).to be_in [true, false] expect(video.infringes_trademark?).to be_in [true, false] expect(video.belongs_to_closed_account?).to be_in [true, false] expect(video.belongs_to_suspended_account?).to be_in [true, false] expect(video.licensed_as_creative_commons?).to be_in [true, false] expect(video.licensed_as_standard_youtube?).to be_in [true, false] expect(video.has_public_stats_viewable?).to be_in [true, false] expect(video.embeddable?).to be_in [true, false] expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_nil expect(video.scheduled_end_time).to be_nil expect(video.concurrent_viewers).to be_nil expect(video.embed_html).to be_a String expect(video.category_title).to be_a String end it { expect{video.update}.to fail } it { expect{video.delete}.to fail.with 'forbidden' } context 'that I like' do before { video.like } it { expect(video).to be_liked } it { expect(video.dislike).to be true } end context 'that I dislike' do before { video.dislike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end context 'that I am indifferent to' do before { video.unlike } it { expect(video).not_to be_liked } it { expect(video.like).to be true } end end context 'given someone else’s live video broadcast scheduled in the future' do let(:id) { 'PqzGI8gO_gk' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_nil expect(video.actual_end_time).to be_nil expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_nil end end context 'given someone else’s past live video broadcast' do let(:id) { 'COOM8_tOy6U' } it 'returns valid live streaming details' do expect(video.actual_start_time).to be_a Time expect(video.actual_end_time).to be_a Time expect(video.scheduled_start_time).to be_a Time expect(video.scheduled_end_time).to be_a Time expect(video.concurrent_viewers).to be_nil end end context 'given an unknown video' do let(:id) { 'not-a-video-id' } it { expect{video.content_detail}.to raise_error Yt::Errors::NoItems } it { expect{video.snippet}.to raise_error Yt::Errors::NoItems } it { expect{video.rating}.to raise_error Yt::Errors::NoItems } it { expect{video.status}.to raise_error Yt::Errors::NoItems } it { expect{video.statistics_set}.to raise_error Yt::Errors::NoItems } it { expect{video.file_detail}.to raise_error Yt::Errors::NoItems } end context 'given one of my own videos that I want to delete' do before(:all) { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: "Yt Test Delete Video #{rand}" } let(:id) { @tmp_video.id } it { expect(video.delete).to be true } end context 'given one of my own videos that I want to update' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let!(:old_title) { video.title } let!(:old_privacy_status) { video.privacy_status } let(:update) { video.update attrs } context 'given I update the title' do # NOTE: The use of UTF-8 characters is to test that we can pass up to # 50 characters, independently of their representation let(:attrs) { {title: "Yt Example Update Video #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the title' do expect(update).to be true expect(video.title).not_to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the description' do let!(:old_description) { video.description } let(:attrs) { {description: "Yt Example Description #{rand} - ®•♡❥❦❧☙"} } specify 'only updates the description' do expect(update).to be true expect(video.description).not_to eq old_description expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the tags' do let!(:old_tags) { video.tags } let(:attrs) { {tags: ["Yt Test Tag #{rand}"]} } specify 'only updates the tag' do expect(update).to be true expect(video.tags).not_to eq old_tags expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'given I update the category ID' do let!(:old_category_id) { video.category_id } let!(:new_category_id) { old_category_id == '22' ? '21' : '22' } context 'passing the parameter in underscore syntax' do let(:attrs) { {category_id: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id expect(video.title).to eq old_title expect(video.privacy_status).to eq old_privacy_status end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {categoryId: new_category_id} } specify 'only updates the category ID' do expect(update).to be true expect(video.category_id).not_to eq old_category_id end end end context 'given I update title, description and/or tags using angle brackets' do let(:attrs) { {title: "Example Yt Test < >", description: '< >', tags: ['<tag>']} } specify 'updates them replacing angle brackets with similar unicode characters accepted by YouTube' do expect(update).to be true expect(video.title).to eq 'Example Yt Test ‹ ›' expect(video.description).to eq '‹ ›' expect(video.tags).to eq ['‹tag›'] end end # note: 'scheduled' videos cannot be set to 'unlisted' context 'given I update the privacy status' do before { video.update publish_at: nil if video.scheduled? } let!(:new_privacy_status) { old_privacy_status == 'private' ? 'unlisted' : 'private' } context 'passing the parameter in underscore syntax' do let(:attrs) { {privacy_status: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {privacyStatus: new_privacy_status} } specify 'only updates the privacy status' do expect(update).to be true expect(video.privacy_status).not_to eq old_privacy_status expect(video.title).to eq old_title end end end context 'given I update the embeddable status' do let!(:old_embeddable) { video.embeddable? } let!(:new_embeddable) { !old_embeddable } let(:attrs) { {embeddable: new_embeddable} } # @note: This test is a reflection of another irrational behavior of # YouTube API. Although 'embeddable' can be passed as an 'update' # attribute according to the documentation, it simply does not work. # The day YouTube fixes it, then this test will finally fail and will # be removed, documenting how to update 'embeddable' too. # @see https://developers.google.com/youtube/v3/docs/videos/update # @see https://code.google.com/p/gdata-issues/issues/detail?id=4861 specify 'does not update the embeddable status' do expect(update).to be true expect(video.embeddable?).to eq old_embeddable end end context 'given I update the public stats viewable setting' do let!(:old_public_stats_viewable) { video.has_public_stats_viewable? } let!(:new_public_stats_viewable) { !old_public_stats_viewable } context 'passing the parameter in underscore syntax' do let(:attrs) { {public_stats_viewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publicStatsViewable: new_public_stats_viewable} } specify 'only updates the public stats viewable setting' do expect(update).to be true expect(video.has_public_stats_viewable?).to eq new_public_stats_viewable expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end it 'returns valid reports for video-related metrics' do # Some reports are only available to Content Owners. # See content owner test for more details about what the methods return. expect{video.views}.not_to raise_error expect{video.comments}.not_to raise_error expect{video.likes}.not_to raise_error expect{video.dislikes}.not_to raise_error expect{video.shares}.not_to raise_error expect{video.subscribers_gained}.not_to raise_error expect{video.subscribers_lost}.not_to raise_error expect{video.videos_added_to_playlists}.not_to raise_error expect{video.videos_removed_from_playlists}.not_to raise_error expect{video.estimated_minutes_watched}.not_to raise_error expect{video.average_view_duration}.not_to raise_error expect{video.average_view_percentage}.not_to raise_error expect{video.annotation_clicks}.not_to raise_error expect{video.annotation_click_through_rate}.not_to raise_error expect{video.annotation_close_rate}.not_to raise_error expect{video.viewer_percentage}.not_to raise_error expect{video.estimated_revenue}.to raise_error Yt::Errors::Unauthorized expect{video.ad_impressions}.to raise_error Yt::Errors::Unauthorized expect{video.monetized_playbacks}.to raise_error Yt::Errors::Unauthorized expect{video.playback_based_cpm}.to raise_error Yt::Errors::Unauthorized expect{video.advertising_options_set}.to raise_error Yt::Errors::Forbidden end end # @note: This test is separated from the block above because, for some # undocumented reasons, if an existing video was private, then set to # unlisted, then set to private again, YouTube _sometimes_ raises a # 400 Error when trying to set the publishAt timestamp. # Therefore, just to test the updating of publishAt, we use a brand new # video (set to private), rather than reusing an existing one as above. context 'given one of my own *private* videos that I want to update' do before { @tmp_video = $account.upload_video 'https://bit.ly/yt_test', title: old_title, privacy_status: old_privacy_status } let(:id) { @tmp_video.id } let!(:old_title) { "Yt Test Update publishAt Video #{rand}" } let!(:old_privacy_status) { 'private' } after { video.delete } let!(:new_scheduled_at) { Yt::Timestamp.parse("#{rand(30) + 1} Jan 2020", Time.now) } context 'passing the parameter in underscore syntax' do let(:attrs) { {publish_at: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title # NOTE: This is another irrational behavior of YouTube API. In short, # the response of Video#update *does not* include the publishAt value # even if it exists. You need to call Video#list again to get it. video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to private has no effect: expect(video.update privacy_status: 'private').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to eq new_scheduled_at # Setting a private (scheduled) video to unlisted/public removes publishAt: expect(video.update privacy_status: 'unlisted').to be true video = Yt::Video.new id: id, auth: $account expect(video.scheduled_at).to be_nil end end context 'passing the parameter in camel-case syntax' do let(:attrs) { {publishAt: new_scheduled_at} } specify 'only updates the timestamp to publish the video' do expect(video.update attrs).to be true expect(video.scheduled_at).to eq new_scheduled_at expect(video.privacy_status).to eq old_privacy_status expect(video.title).to eq old_title end end end # @note: This should somehow test that the thumbnail *changes*. However, # YouTube does not change the URL of the thumbnail even though the content # changes. A full test would have to *download* the thumbnails before and # after, and compare the files. For now, not raising error is enough. # Eventually, change to `expect{update}.to change{video.thumbnail_url}` context 'given one of my own videos for which I want to upload a thumbnail' do let(:id) { $account.videos.where(order: 'viewCount').first.id } let(:update) { video.upload_thumbnail path_or_url } context 'given the path to a local JPG image file' do let(:path_or_url) { File.expand_path '../thumbnail.jpg', __FILE__ } it { expect{update}.not_to raise_error } end context 'given the path to a remote PNG image file' do let(:path_or_url) { 'https://bit.ly/yt_thumbnail' } it { expect{update}.not_to raise_error } end context 'given an invalid URL' do let(:path_or_url) { 'this-is-not-a-url' } it { expect{update}.to raise_error Yt::Errors::RequestError } end end # @note: This test is separated from the block above because YouTube only # returns file details for *some videos*: "The fileDetails object will # only be returned if the processingDetails.fileAvailability property # has a value of available.". Therefore, just to test fileDetails, we use a # different video that (for some unknown reason) is marked as 'available'. # Also note that I was not able to find a single video returning fileName, # therefore video.file_name is not returned by Yt, until it can be tested. # @see https://developers.google.com/youtube/v3/docs/videos#processingDetails.fileDetailsAvailability context 'given one of my own *available* videos' do let(:id) { 'yCmaOvUFhlI' } it 'returns valid file details' do expect(video.file_size).to be_an Integer expect(video.file_type).to be_a String expect(video.container).to be_a String end end end
class AddWDayToWaitTime < ActiveRecord::Migration def change add_column :wait_times, :wday, :integer end end
class Account::IncomesController < Account::ApplicationController def index @income = current_user.incomes.build @incomes = Account::IncomeDecorator.decorate_collection( Incomes::CurrentMonthsQuery.call(user: current_user) ) @labels = current_user.income_labels end def create result = Incomes::Create.call( user: current_user, params: income_params ) if result.success? redirect_to account_incomes_path else @income = result.income @incomes = Account::IncomeDecorator.decorate_collection( Incomes::CurrentMonthsQuery.call(user: current_user) ) @labels = current_user.income_labels flash[:error] = @income.errors.full_messages.join("\n") render :index end end def edit @income = current_user.incomes.find_by(id: params[:id]) @labels = current_user.income_labels end def update income = current_user.incomes.find_by(id: params[:id]) result = Incomes::Update.call(income: income, params: income_params) if result.success? redirect_to account_incomes_path else @income = result.income @labels = current_user.income_labels render :edit end end def destroy current_user.incomes.destroy redirect_to account_incomes_path end private def income_params params.require(:income).permit( :id, :label_id, :amount_cents, :amount_currency, :received_at, :spend_till ) end end
class Trip < ActiveRecord::Base attr_protected :user_id belongs_to :customer belongs_to :driver belongs_to :location belongs_to :user validates_associated :driver validates_presence_of :driver_id, :user_id validates_presence_of :location_id, :unless => :skipped before_create :set_location_fees, :unless => :skipped after_create :set_driver_trip_dates private def set_location_fees write_attribute(:fee, location.fee) unless fee.present? write_attribute(:charge, location.charge) unless charge.present? end def set_driver_trip_dates if scheduled driver.last_scheduled_trip = created_at else driver.last_random_trip = created_at end if skipped driver.skipped = true else driver.skipped = false end driver.save end end
require 'array_core_extensions' class Board < ActiveRecord::Base serialize :grid before_create :default_grid def get_cell(x, y) grid[y][x] end def set_cell(x, y, value) if get_cell(x, y).blank? grid[y][x] = value save else 'cannot overide cell value' end end def status return :winner if winner? return :tie if tie? 'Game in Progress' end private def default_grid self.grid ||= Array.new(3) { Array.new(3) { '' } } end def tie? grid.flatten.none_empty? end def winner? winning_combinations.each do |winning_position| next if winning_position.all_empty? return true if winning_position.all_same? end false end def winning_combinations rows + columns + diagonals end def rows grid end def columns grid.transpose end def diagonals [left_diagonal, right_diagonal] end def left_diagonal [get_cell(0, 0), get_cell(1, 1), get_cell(2, 2)] end def right_diagonal [get_cell(0, 2), get_cell(1, 1), get_cell(2, 0)] end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :contact_request do name "Francis Gulotta" email "hello@wizarddevelopment.com" phone "9175551212" business_name "Wizard Development" message "I need a website to sell my stuff" dev_team "I have one" product_status "Middle" end end
class AddUniqueHashToAnswer < ActiveRecord::Migration def change add_column :answers, :unique_hash, :string add_index :answers, :unique_hash, unique: true end end
class Ability include CanCan::Ability def initialize(user) alias_action :edit, :update, :destroy, :my_posts, to: :access alias_action :index, to: :read_feed alias_action :show, to: :view_post if user can :read_feed, Post can :view_post, Post do |post| (post.posted?) || (post.user_id == user.id) end can :create, Post can :access, Post, user_id: user.id else can :read_feed, Post can :view_post, Post do |post| post.posted? end end can :create, Comment end end
class AddListeningToServerUrl < ActiveRecord::Migration def change add_column :server_urls, :listening, :boolean, :after => :peer_verify, :null => false, :default => false end end
class ContactsController < ApplicationController def index @contacts = Contact.order(name: :asc) render 'index' end def new end def create # Create new Contact from params[:contact] contact = Contact.new( :name => params[:contact][:name], :address => params[:contact][:address], :phone => params[:contact][:phone], :email => params[:contact][:email] ) if !contact[:name].blank? and !contact[:address].blank? contact.save redirect_to("/contacts") else flash[:alert] = "Please fill out the name and address of the contact" render '/contacts/new' end # Render contact's attributes # render(:text => contact.attributes) end def show contact_id = params[:id] @contact = Contact.find_by(id: contact_id) end end
require 'rails_helper' RSpec.describe UsersController, :type => :controller do describe 'GET #show' do let!(:alice){ FactoryGirl.create :user } let!(:symptom){ FactoryGirl.create :symptom, user: alice } context '自分自身がアクセスしたとき' do before do login(alice) get :show, id:alice.id end it '@userに、リクエストしたUser オブジェクトが格納されていること' do expect(assigns(:user)).to eq(alice) end it '@symptoms に、userのsymptomが格納されていること' do expect(assigns(:symptoms)).to match_array([symptom]) end it 'showテンプレートをrenderしていること' do expect(response).to render_template :show end end context '他のユーザがアクセスしたとき' do let!(:bob){ FactoryGirl.create :user } before do login(bob) get :show, id:alice.id end it '@userに、リクエストしたUser オブジェクトが格納されていること' do expect(assigns(:user)).to eq(alice) end it '@symptoms に、userのsymptomが格納されていること' do expect(assigns(:symptoms)).to match_array([symptom]) end it 'showテンプレートをrenderしていること' do expect(response).to render_template :show end end context 'guestがアクセスしたとき' do before do get :show, id:alice.id end it '@userに、リクエストしたUser オブジェクトが格納されていること' do expect(assigns(:user)).to eq(alice) end it '@symptoms に、userのsymptomが格納されていること' do expect(assigns(:symptoms)).to match_array([symptom]) end it 'showテンプレートをrenderしていること' do expect(response).to render_template :show end end end describe 'DELETE #destroy' do let!(:alice){ FactoryGirl.create :user } context '未ログインユーザがアクセスしたとき' do before { delete :destroy, id:alice.id } it_should_behave_like '認証が必要なページ' end context 'ログインユーザかつイベントを作成したユーザがクセスしたとき' do before { login(alice) } it 'Userレコードが1件減っていること' do expect{ delete :destroy, id: alice.id }. to change { User.count }.by(-1) end it 'showテンプレートをrenderしていること' do delete :destroy, id: alice.id ## noticeのテストはできないみたいなので、省いています。 # expect(response).to redirect_to( :controller => 'welcome', :action => 'index', :notice => '退会しました' ) expect(response).to redirect_to( :controller => 'welcome', :action => 'index' ) end end context 'ログインユーザかつイベントを作成していないユーザがクセスしたとき' do let!(:not_owner) { FactoryGirl.create :user } before { login(not_owner) } it 'Userレコードが減っていないこと' do expect{ delete :destroy, id: alice.id }. not_to change { User.count } end it 'error404テンプレートをrenderしていること' do delete :destroy, id: alice.id expect(response).to render_template :error404 end end end end
# encoding: utf-8 require 'colorize' class Board attr_accessor :board def initialize @board = Array.new(8) { Array.new(8) {nil} } end def set_starting_pieces piece_types = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook] piece_types.each_with_index do |piece_type, index| @board[0][index] = piece_type.new(:black) @board[7][index] = piece_type.new(:white) @board[1][index] = Pawn.new(:black) @board[6][index] = Pawn.new(:white) end end def clone(board) board.board = @board.deep_dup end # REV: I liked the display. Very clean! def display_board display_board = @board.deep_dup display_board.each do |row| row.map! {|item| item = item.display if item.is_a?(Piece)} end p ["", "0", "1", "2", "3", "4", "5", "6", "7"] display_board.each_with_index {|row, index| puts " #{index}: #{row} #{index}" } p ["", "0", "1", "2", "3", "4", "5", "6", "7"] nil end def validity(move) start_coor, end_coor = move[0], move[1] player_color = move[2] piece = @board[start_coor[0]][start_coor[1]] delta = [end_coor[0] - start_coor[0], end_coor[1] - start_coor[1]] unless moving_off_board?(end_coor) {:move_valid => false, :reason => "You can't move off the board"} end unless space_is_piece?(start_coor) return {:move_valid => false, :reason => "Nil's can't move silly."} end unless own_piece?(start_coor, player_color) return {:move_valid => false, :reason => "You don't own that piece!"} end unless piece.can_move?(delta) return {:move_valid => false, :reason => "That piece can't move like that"} end if own_piece?(end_coor, player_color) return {:move_valid => false, :reason => "One of your pieces is at the end location"} end unless clear_path?(move, delta) return {:move_valid => false, :reason => "Your path is blocked!"} end unless pawn_valid_move?(move, delta) return {:move_valid => false, :reason => "Pawns can't move like that"} end {:move_valid => true} end def space_is_piece?(current_coord) @board[current_coord[0]][current_coord[1]].is_a?(Piece) end def moving_off_board?(end_coord) (end_coord[0] >= 0 && end_coord[0] <= 7) && (end_coord[1] >= 0 && end_coord[1] <= 7) end def own_piece?(coor, player_color) target = @board[coor[0]][coor[1]] return target.color == player_color unless target.nil? false end def pawn_valid_move?(move, delta) start_coor, end_coor = move[0], move[1] return true if @board[start_coor[0]][start_coor[1]].name != :p if delta[0] == delta[1] || (delta[0] * -1) == delta[1] return false if @board[end_coor[0]][end_coor[1]] == nil @board[end_coor[0]][end_coor[1]].color != move[2] elsif delta[1] == 0 @board[end_coor[0]][end_coor[1]] == nil end end def clear_path? (move, delta) #REV: All of these methods are very easy to read. Great! start_coor, end_coor = move[0], move[1] piece = @board[start_coor[0]][start_coor[1]] case when [:kn,:p,:ki].include?(piece.name) true when piece.name == :r rook_clear_path_helper(start_coor, end_coor) when piece.name == :b bishop_clear_path_helper(start_coor, end_coor, delta) when piece.name == :q queen_clear_path_helper(start_coor, end_coor, delta) end end def rook_clear_path_helper(start_coor, end_coor) if start_coor[0] == end_coor[0] #horizontal lower = start_coor[1] > end_coor[1] ? end_coor[1] : start_coor[1] #REV: Can these be combined? upper = start_coor[1] < end_coor[1] ? end_coor[1] : start_coor[1] (lower+1...upper).each do |col| return false if @board[start_coor[0]][col] != nil end elsif start_coor[1] == end_coor[1] #vertical lower = start_coor[0] > end_coor[0] ? end_coor[0] : start_coor[0] upper = start_coor[0] < end_coor[0] ? end_coor[0] : start_coor[0] (lower+1...upper).each do |row| return false if @board[row][start_coor[1]] != nil end end true end def bishop_clear_path_helper(start_coor, end_coor, delta) y_sign = delta[0] > 0 ? :+ : :- x_sign = delta[1] > 0 ? :+ : :- i = start_coor[0] # ~= y j = start_coor[1] # ~= x until [i,j] == end_coor unless [i,j] == start_coor return false if @board[i][j] != nil end y_sign == :+ ? i += 1 : i -= 1 x_sign == :+ ? j += 1 : j -= 1 end true end def queen_clear_path_helper(start_coor, end_coor, delta) if (delta[0] == 0) or (delta[1] == 0) rook_clear_path_helper(start_coor, end_coor) else bishop_clear_path_helper(start_coor, end_coor, delta) end end def move_piece(move) @board[move[1][0]][move[1][1]] = @board[move[0][0]][move[0][1]] @board[move[0][0]][move[0][1]] = nil end def check?(defending_color) attacking_color = defending_color == :black ? :white : :black attacking_pieces_coor = get_player_pieces_coor(attacking_color) defending_king_coor = get_king_coor(defending_color) attacking_pieces_coor.inject(false) do |init, piece| init or validity([piece, defending_king_coor, attacking_color])[:move_valid] end end def get_player_pieces_coor(player_color) #REV: Could you combine these somehow or write a method to be called on each? coors = [] @board.each_with_index do |row, y_index| row.each_with_index do |space, x_index| unless space == nil coors << [y_index, x_index] if space.color == player_color end end end coors end def get_king_coor(player_color) king_coor = [] @board.each_with_index do |row, y_index| row.each_with_index do |space, x_index| unless space == nil if space.name == :ki and space.color == player_color king_coor = [y_index, x_index] end end end end king_coor end def checkmate?(defending_color) # defending = are they checkmated? attacking_color = defending_color == :black ? :white : :black defending_pieces_coor = get_player_pieces_coor(defending_color) defending_pieces_coor.each do |piece_coor| (0..7).each do |y_index| (0..7).each do |x_index| test_board = Board.new self.clone(test_board) if validity([piece_coor, [y_index, x_index], defending_color])[:move_valid] test_board.move_piece([piece_coor, [y_index, x_index], defending_color]) unless test_board.check?(defending_color) # if check == false return false end end end end end true end def get_outcome(current_player_color) resting_player_color = current_player_color == :black ? :white : :black if checkmate?(current_player_color) :self_in_checkmate elsif checkmate?(resting_player_color) :opponent_in_checkmate elsif check?(current_player_color) :self_in_check elsif check?(resting_player_color) :opponent_in_check else :continue end end end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] skip_before_action :verify_authenticity_token before_action :authenticate_user! # GET /users # GET /users.json def index @users = User.all end def ban_user user_to_ban = User.find(params[:id]) if not user_to_ban.is_active redirect_back(fallback_location: root_path); flash[:danger] = "User is already banned" else user_to_ban.update(is_active:false) redirect_back(fallback_location: root_path); flash[:success] = "User banned" end end # GET /users/1 # GET /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit end # POST /users # POST /users.json def create end def create_admin @user = User.new(user_params) if @user.save UserRole.create(role_id:2, user_id:@user.id) redirect_back(fallback_location: root_path); flash[:success] = "Administrator successfully created" else redirect_back(fallback_location: root_path); flash[:danger] = "Error creating administrator" end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update @user_to_update = User.find(user_params[:id]) if @user_to_update.update(user_params) redirect_back(fallback_location: root_path); flash[:success] = "User was successfully edited" else redirect_back(fallback_location: root_path); flash[:danger] = "Error editing user" end end # DELETE /users/1 # DELETE /users/1.json def destroy @user.destroy respond_to do |format| format.html { redirect_back(fallback_location: root_path); flash[:success] = 'User was successfully destroyed.' } format.json { head 200 } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:id, :email, :password, :is_active) end end
class Addition < ActiveRecord::Migration def change add_column :transactions,:approved_by,:integer add_column :transactions,:approve,:string end end
class HistoryController < ApplicationController before_action :authenticate_user! include CurrentCart before_action :set_cart, only: [:create] def index @history = current_user.line_items.where.not(:order_id =>"NULL").order('created_at DESC') end end
class DataFile < ActiveRecord::Base has_attached_file :photo, :styles => { :small => "75x75>" } validates_attachment_presence :photo, :message => "Du glemte å laste opp bildet" end
FactoryGirl.define do factory :seller do ##GENERAL factory :valid_seller, class: Seller do email "test@test.com" password "password" end factory :null_email, class: Seller do email nil password "password" end factory :null_password, class: Seller do email "test@test.com" password nil end factory :email_limit, class: Seller do email "test@tkdkjkdkkdkdkdkdkkdkdkdkdllllllllllllllllllllllllkdkdkdkkdkkdkdkdkdkdk.com" password "password" end factory :pw_limit, class: Seller do email "test@test.com" password "test" end factory :invalid_seller, class: Seller do email "test@test.com" password "password" password_confirmation "password123" end end end
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time before_action :configure_permitted_paramters, if: :devise_controller? before_action :maintenance_mode? before_action :run_scheduler before_action :authenticate_user! before_action :authorize_user_for_course, except: [:action_no_auth ] before_action :authenticate_for_action before_action :update_persistent_announcements rescue_from CourseUserDatum::AuthenticationFailed do |e| COURSE_LOGGER.log("AUTHENTICATION FAILED: #{e.user_message}, #{e.dev_message}") flash[:error] = e.user_message redirect_to :controller => "home", :action => "error" end # this is where Error Handling is configured. this routes exceptions to # the error handler in the HomeController, unless we're in development mode # # the policy is basically a replica of Rails's default error handling policy # described in http://guides.rubyonrails.org/action_controller_overview.html#rescue unless Rails.env.development? # this doesn't appear to be getting called -Dan #rescue_from ActiveRecord::RecordNotFound, :with => :render_404 rescue_from Exception, with: :render_error end def self.autolabRequire(path) if (Rails.env == "development") then $".delete(path) end require(path) end @@global_whitelist = {} def self.action_auth_level(action, level) raise ArgumentError.new("The action must be specified.") if action.nil? raise ArgumentError.new("The action must be symbol.") unless action.is_a? Symbol raise ArgumentError.new("The level must be specified.") if level.nil? raise ArgumentError.new("The level must be symbol.") unless level.is_a? Symbol unless CourseUserDatum::AUTH_LEVELS.include?(level) raise ArgumentError.new("#{level.to_s} is not an auth level") end controller_whitelist = (@@global_whitelist[self.controller_name.to_sym] ||= {}) raise ArgumentError.new("#{action.to_s} already specified.") if controller_whitelist[action] controller_whitelist[action] = level end def self.action_no_auth(action) skip_before_action :verify_authenticity_token, :authenticate_user! skip_filter :configure_permitted_paramters => [action] skip_filter :maintenance_mode => [action] skip_filter :run_scheduler => [action] skip_filter :authenticate_user => [action] skip_before_filter :authorize_user_for_course, only: [action] skip_filter :authenticate_for_action => [action] skip_before_filter :update_persistent_announcements, only: [action] end protected def configure_permitted_paramters devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:email) } devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :first_name, :last_name, :password, :password_confirmation) } devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:email, :password, :password_confirmation, :current_password) } end def authentication_failed(user_message=nil, dev_message=nil) user_message ||= "You are not authorized to view this page" if user_signed_in? dev_message ||= "For user #{current_user.email}" else dev_message ||= "Before initial user authentication." end raise CourseUserDatum::AuthenticationFailed.new(user_message, dev_message) end def authenticate_for_action controller_whitelist = @@global_whitelist[params[:controller].to_sym] return if controller_whitelist.nil? level = controller_whitelist[params[:action].to_sym] return if level.nil? authentication_failed unless @cud.has_auth_level?(level) end protect_from_forgery def verify_authenticity_token msg = "Invalid request! Please go back, reload the " + "page and try again. If you continue to see this error. " + " please contact the Autolab Development team at the " + "contact link below" if not verified_request? then authentication_failed(msg) end end def maintenance_mode? # enable/disable maintenance mode with this switch: if false unless @user.administrator? redirect_to "/maintenance.html" end end end # def authenticate_user # # development # if Rails.env == "development" # if cookies[:dev_user] then # @username = cookies[:dev_user] # else # redirect_to controller: :home, action: :developer_login and return # end # # # production # else # # request.remote_user set by Shibboleth (WebLogin) # if request.remote_user # @username = request.remote_user.split("@")[0] # else # flash[:error] = "You are not logged in?" # redirect_to :controller => :home, :action => :error and return # end # end # end def authorize_user_for_course @course = Course.find(params[:course_id] || params[:id]) unless @course flash[:error] = "Course #{params[:course]} does not exist!" redirect_to controller: :home, action: :error and return end # set course logger begin COURSE_LOGGER.setCourse(@course) rescue Exception => e flash[:error] = e.to_s redirect_to controller: :home, action: :error and return end uid = current_user.id # don't allow sudoing across courses if (session[:sudo]) then if (@course.id == session[:sudo]["course_id"]) then uid = session[:sudo]["user_id"] else session[:sudo] = nil end end # set @cud cud, reason = CourseUserDatum.find_or_create_cud_for_course @course, uid case reason when :found @cud = cud when :admin_created @cud = cud flash[:info] = "Administrator user added to course" when :admin_creation_error flash[:error] = "Error adding user: #{current_user.email} to course" redirect_to controller: :home, action: :error and return when :unauthorized flash[:error] = "User #{current_user.email} is not in this course" redirect_to controller: :home, action: :error and return end # check if course was disabled if @course.disabled? and !@cud.has_auth_level?(:instructor) then flash[:error] = "Your course has been disabled by your instructor. Please contact them directly if you have any questions" redirect_to controller: :home, action: :error and return end # should be able to unsudo from an invalid user and # an invalid user should be able to make himself valid through edit page invalid_cud = !@cud.valid? nicknameless_student = @cud.student? && @cud.nickname.blank? in_edit_or_unsudo = (params[:controller] == "course_user_data") && (params[:action] == "edit" or params[:action] == "update" or params[:action] == "unsudo") if (invalid_cud or nicknameless_student) and !in_edit_or_unsudo then flash[:error] = "Please complete all of your account information before continuing" redirect_to edit_course_course_user_datum_path(id: @cud.id, course_id: @cud.course.id) end end def run_scheduler actions = Scheduler.where("next < ?",Time.now()) for action in actions do action.next = Time.now + action.interval action.save() puts "Executing #{File.join(Rails.root,action.action)}" begin pid = fork do # child process @course = action.course modName = File.join(Rails.root,action.action) require "#{modName}" Updater.update(@course) end Process.detach(pid) rescue Exception => e puts e puts e.message puts e.backtrace.inspect end end end def update_persistent_announcements @persistent_announcements = Announcement.where("persistent and (course_id=? or system)", @course.id) end def pluralize(count, singular, plural = nil) "#{count || 0} " + ((count == 1 || count =~ /^1(\.0+)?$/) ? singular : (plural || singular.pluralize)) end private # called on Exceptions. Shows a stack trace to course assistants, and above. # Shows good ol' Donkey Kong to students def render_error(exception) # use the exception_notifier gem to send out an e-mail to the notification list specified in config/environment.rb ExceptionNotifier.notify_exception(exception) #TODO: hide stack traces from students after the beta. leave @error undefined to hide stack traces @error = exception render "home/error" end # called on ActiveRecord::RecordNotFound exception. # Redirect user to the 404 page without error notification def render_404 render file: "public/404.html", layout: false end end
# -*- encoding : utf-8 -*- # CRUD dla kategorii # # Kod wygenerowany automatycznie przez szablon Rails. # # Jedyna zmiana to przekodowanie zdjęć do Base64 w POST i PUT. # class CategoriesController < ApplicationController before_filter :require_admin layout 'admin' # GET /categories # GET /categories.json def index @categories = Category.all respond_to do |format| format.html # index.html.erb format.json { render :json => @categories } end end # GET /categories/1.json def show @category = Category.find(params[:id]) respond_to do |format| format.html { render :layout => 'bare' } # show.html.erb format.json { render :json => @category } end end # GET /categories/new # GET /categories/new.json def new @category = Category.new respond_to do |format| format.html { render :layout => 'bare' } format.json { render :json => @category } end end # GET /categories/1/edit def edit @category = Category.find(params[:id]) render :layout => 'bare' end # POST /categories # POST /categories.json def create icon = nil if !params[:category][:icon].blank? icon = Base64.encode64(params[:category][:icon].read) end @category = Category.new(:name => params[:category][:name], :icon => icon) respond_to do |format| if @category.save format.html { redirect_to @category, :notice => 'Kategoria została utworzona' } format.json { render :json => @category, :status => :created, :location => @category } else format.html { render :action => "new", :layout => 'bare' } format.json { render :json => @category.errors, :status => :unprocessable_entity } end end end # PUT /categories/1 # PUT /categories/1.json def update icon = nil if !params[:category][:icon].blank? icon = Base64.encode64(params[:category][:icon].read) end @category = Category.find(params[:id]) respond_to do |format| if @category.update_attributes(:name => params[:category][:name], :icon => icon) format.html { redirect_to @category, :notice => 'Kategoria została zaktualizowana' } format.json { head :no_content } else format.html { render :action => "edit", :layout => 'bare' } format.json { render :json => @category.errors, :status => :unprocessable_entity } end end end # DELETE /categories/1 # DELETE /categories/1.json def destroy @category = Category.find(params[:id]) @category.destroy respond_to do |format| format.html { redirect_to categories_url } format.json { head :no_content } end end end
require "spec_helper" feature 'Editing Users' do let!(:user) { FactoryGirl.create(:user) } let!(:admin) { FactoryGirl.create(:admin) } before do sign_in_as! admin visit '/' click_link 'Admin' click_link 'Users' click_link user.to_s click_link 'Edit User' end scenario "Updating a user's details" do fill_in "Email", with: "newguy@example.com" click_button "Update User" expect(page).to have_content("User successfully updated.") within("h2") do expect(page).to have_content("newguy@example.com") expect(page).to_not have_content(user.email) end end scenario "Toggling a user's admin ability" do check "Administrator" click_button 'Update User' expect(page).to have_content("User successfully updated.") within("h2") do expect(page).to have_content("#{user.email} (Admin)") end end end
class EmployeesController < ApplicationController before_action :set_employee, :only => [:edit, :destroy, :update] def index @employees=Employee.all end def new @employee=Employee.new end def edit end def update respond_to do |format| if @employee.update(employee_params) format.html{ redirect_to employee_url(@employee) } format.js else format.html{render :edit} format.js end end end def destroy @employee.destroy redirect_to employees_path end def create @employee=Employee.new(employee_params) respond_to do |format| if @employee.save format.html{ redirect_to employees_url } format.js else format.html{render :new} format.js end end end private def employee_params params.require(:employee).permit(:name, :department_id, :position_id, :sex, :phone, :telephone, :englishname, :qq, :email, :birthday) end def set_employee @employee=Employee.find(params[:id]) end end
class Tweet attr_accessor :text, :user_id, :id def self.setup_table sql = <<-SQL CREATE TABLE tweets ( id INTEGER PRIMARY KEY, text TEXT, user_id INTEGER ); SQL DB.execute(sql) end def initialize(tweet_hash) tweet_hash.each{|key, val| self.send("#{key}=", val)} end def save if !!@id sql = <<-SQL UPDATE tweets SET text, user_id VALUES (?, ?) WHERE id = ? SQL DB.execute(sql, self.text, self.user_id, self.id) else sql = <<-SQL INSERT INTO tweets (text, user_id) VALUES (?, ?); SQL DB.execute(sql, self.text, self.user_id) end end end
class ApplicationController < ActionController::Base # This will automatically include a security token in all forms and Ajax requests generated by Rails. # If the security token doesn't match what was expected, an exception will be thrown. protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? before_action :authenticate_user! # handles unautorized errors and show message on the current page # rescue_from CanCan::AccessDenied do |exception| # respond_to do |format| # format.json {head :forbidden} # format.html {redirect_to main_app.root_url, :alert => exception.message} # end # end rescue_from CanCan::AccessDenied do |exception| render :file => "#{Rails.root}/public/403.html", :status => 403, :layout => false end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :role]) end end
module HomeHelper def resource User.new end def resource_name :user end def devise_mapping @devise_mapping ||= Devise.mappings[:user] end REGEXEN = {} HTML_TAGS = %w(a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup command data datagrid datalist dd del details dfn div dl dt em embed eventsource fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd keygen label legend li link mark map menu meta meter nav noscript object ol optgroup option output p param pre progress q ruby rp rt s samp script section select small source span strong style sub summary sup table tbody td textarea tfoot th thead time title tr track u ul var video wbr) ADDITIONAL_HTML_TAG = %w(&nbsp; &copy;) REGEXEN[:HTML_TAGS] = /<\/?(#{HTML_TAGS.join('|')}).*?\/?>/im REGEXEN[:ADDITIONAL_HTML_TAG] = /(#{ADDITIONAL_HTML_TAG.join('|')};?)/m def remove_html_tag str return '' if str.nil? str.gsub(REGEXEN[:HTML_TAGS], ' ').gsub(REGEXEN[:ADDITIONAL_HTML_TAG], ' ') end def get_image_url(topic) content = topic.posts.first.text doc = Nokogiri::HTML(content) img_srcs = doc.css('img').map { |i| i['src'] } first_img = img_srcs.first end end
module Engine #Base game object. Each game object (npc, castle, chest..) should extend this class class BaseGameObject attr_accessor :x, :y, :type, :name def initialize(x, y, type, name) @x = x @y = y @type = type @name = name end def move(x, y) @x += x @y += y end public :move def to_s "Name: #{@name}, Type: #{@type}, Position: #{@x}, #{@y}" end end end
class Product < ActiveRecord::Base end class CreateProducts < ActiveRecord::Migration def self.up create_table :products do |t| t.string :name end end def self.down drop_table :orders end end
class Parish < ActiveRecord::Base belongs_to :county has_many :towns, order: 'name' has_many :users def towns_for_select towns.map{ |x| [x.name, x.name] } end def to_s name end end
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require "Parser" describe "Parser" do let(:parser) {Parser.new } it "empty string should have main node" do parser.parse("") end it "parses a literal node" do parser.parse("1") end it "parses an if statement do" do parser.parse("echo") end end
require 'faye/websocket' require 'eventmachine' module SlackBotSlim class Receiver def initialize(url, bot) @url = url @bot = bot @restart = true end def start while @restart EM.run do ws = Faye::WebSocket::Client.new(@url) ws.on :open do |event| @bot.log 'Successfully connected.' end ws.on :message do |event| handle_event event end ws.on :close do |event| @bot.log "connection closed: [%s] '%s'" % [event.code, event.reason] self.stop end Signal.trap("INT") { self.stop } Signal.trap("TERM") { self.stop } end end end def stop(mode = nil) @restart = (mode == :restart) EM.stop if @restart @bot.log 'restart connection' else @bot.log "stopped" end end private def handle_event(event) data = JSON.parse(event.data) case type = data["type"].to_sym when :message @bot.handle_message data when :team_migration_started @bot.log "#{type}: stop and restart" self.stop :restart when :reconnect_url @url = data['url'] else # do nothing # if you want add reactions, # refar to https://api.slack.com/rtm # ex. user or team add/change. print '.' end end end end
Rails.application.routes.draw do devise_for :users root to: 'blogs#index' resources :blogs do resources :reviews, only: [:show, :new, :create] end end
class Maintaining < ActiveRecord::Base belongs_to :topic belongs_to :user def self.find_maintainings_to_be_verified_by_topic_creator(page,user_id) Maintaining.paginate_by_sql ['select * from maintainings where topic_id in(select id from topics where creator_id =?) AND verified = 0',user_id], :page=>page, :per_page=>5 end def self.maintainings_of_logon_user(user) user.maintainings end ####################### #实例方法 ####################### def topic Topic.find self.topic_id end def maintainer ExtUser.find self.maintainer_id end end
require 'rails_helper' RSpec.describe 'Competition show page' do before :each do @team_1 = Team.create(hometown: "Dallas", nickname: "The Boots") @player_1 = @team_1.players.create(name: "Tony", age: 20) @player_2 = @team_1.players.create(name: "Bartholomew", age: 30) @player_3 = @team_1.players.create(name: "Wayne", age: 25) @team_2 = Team.create(hometown: "South Park", nickname: "The Duds") @player_4 = @team_2.players.create(name: "Jen", age: 19) @player_5 = @team_2.players.create(name: "Lisa", age: 32) @player_6 = @team_2.players.create(name: "Brody", age: 22) @competition_1 = Competition.create(name: "The Mad Dash", location: "Broadway", sport: "Running") @team_comp_1 = TeamCompetition.create(team: @team_1, competition: @competition_1) @team_comp_2 = TeamCompetition.create(team: @team_2, competition: @competition_1) end it 'displays competition name, location, and sport' do visit competition_path(@competition_1) expect(page).to have_content(@competition_1.name) expect(page).to have_content(@competition_1.location) expect(page).to have_content(@competition_1.sport) end it 'displays team information' do visit competition_path(@competition_1) expect(page).to have_content(@team_1.nickname) expect(page).to have_content(@team_1.hometown) expect(page).to have_content(@team_2.nickname) expect(page).to have_content(@team_2.hometown) end it 'displays average player age' do visit competition_path(@competition_1) expect(page).to have_content(@team_1.avg_player_age) end it 'contains link to register a new team' do visit competition_path(@competition_1) click_link "Register a New Team" expect(current_path).to eq(new_team_path) end end
require 'test_helper' class ProblemTypesHelperTest < ActionView::TestCase def setup @problem_type = ProblemType.new @fixture_problem_type = problem_types(:simp_no_zero_problem_type) @lesson = lessons(:monomial_factors_of_polynomials_lesson) end test "level_count_msg multiple" do @problem_type.stubs(:level_count).returns(7) assert_equal "7 Levels", level_count_msg(@problem_type) end test "level_count_msg singular" do @problem_type.stubs(:level_count).returns(1) assert_equal "1 Level", level_count_msg(@problem_type) end test "level_count_msg zip" do @problem_type.stubs(:level_count).returns(0) assert_equal "0 Levels", level_count_msg(@problem_type) end test "display_tag_list with no tags" do assert_equal "", display_tag_list(@problem_type) end test "display tag list" do @problem_type.tag_list = "Movies, Music, Coffee" assert_equal "Tags: <span class='tag'>Movies</span><span class='tag'>Music</span><span class='tag'>Coffee</span>", display_tag_list(@problem_type) end test "delete level returns nothing if level has math problems" do level = ProblemLevel.new(:level_number => '23') level.build_problem_type(:title => "abra") level.math_problems.build(:question_markup => "some markup", :answer_markup => "some answer") assert_equal "", delete_level(level) end test "delete level returns delete link if level is empty" do level = ProblemLevel.new(:level_number => '17') level.build_problem_type(:title => 'my prob type') destroy_link = link_to('Delete Level', '/problem_types/my-prob-type/problem_levels/17', :confirm => 'Are you sure?', :method => :delete) assert_equal destroy_link, delete_level(level) end test "delete_problem_type_link returns nothing if problem type has levels" do @problem_type.problem_levels.build assert_equal "", delete_problem_type_link_if_empty(@problem_type) end test "delete_problem_type_link returns link if problem type is empty" do @problem_type.title = "wkrp" destroy_link = render(:partial => 'problem_types/delete_problem_type', :locals => {:type => @problem_type}) assert_equal destroy_link, delete_problem_type_link_if_empty(@problem_type) end test "empty_problem_type_message" do assert_equal MathHotSpotErrors::Message::NO_PROBLEMS_DEFINED_FOR_PROBLEM_TYPE, empty_problem_type_message end test "category choices" do algebra = Subject.new(:title => 'Algebra') geometry = Subject.new(:title => 'Geometry') fractions = Category.new(:title => "Fractions", :subject => algebra) hexagons = Category.new(:title => "Hexagons and Other Fun Stuff", :subject => geometry) graphing = Category.new(:title => "Graphing", :subject => algebra) categories = [fractions, graphing, hexagons] Category.stubs(:order).with('subject_id').returns(categories) Category.any_instance.stubs(:id).returns(47) expected_options = [['Algebra -- Fractions', 47], ['Algebra -- Graphing' ,47], ['Geometry -- Hexagons and Other Fun Stuff', 47]] assert_equal expected_options, category_choices end test "add_to_current_lesson_link_if_applicable renders partial if current lesson set in session" do session[:current_lesson_id] = @lesson.id partial = render :partial => "problem_types/add_problem_type_to_current_lesson", :locals => {:lesson => @lesson, :problem_type => @problem_type} assert_equal partial, add_to_current_lesson_link_if_applicable(@problem_type) end test "add_to_current_lesson_link_if_applicable returns nil if current lesson is NOT set in session" do assert_nil add_to_current_lesson_link_if_applicable(@problem_type) end end
namespace :check do namespace :migrate do task fix_folder_cached_value: :environment do started = Time.now.to_i ProjectMedia.select('project_medias.id, p.title as p_title') .joins("INNER JOIN projects p on p.id = project_medias.project_id") .find_in_batches(batch_size: 2500) do |pms| pms.each do |pm| print '.' Rails.cache.write("check_cached_field:ProjectMedia:#{pm.id}:folder", pm.p_title) end end minutes = ((Time.now.to_i - started) / 60).to_i puts "[#{Time.now}] Done in #{minutes} minutes." end end end
class P11Kit < Formula homepage "http://p11-glue.freedesktop.org" url "http://p11-glue.freedesktop.org/releases/p11-kit-0.18.4.tar.gz" sha256 "df5424ec39e17c2b3b98819bf772626e9b8c73871a8b82e54151f6297d8575fd" bottle do sha1 "1f75969e6cbf89921ba4d205e093c6d7bddd755e" => :yosemite sha1 "4baec782e0d55aacb458bcd752d32f4d63de4424" => :mavericks sha1 "1f16ca29e9c9b38ec832ce04c3802d439c2ba896" => :mountain_lion end option :universal depends_on "pkg-config" => :build depends_on "libtasn1" def install ENV.universal_binary if build.universal? system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--disable-trust-module" system "make" system "make", "check" system "make", "install" end test do system "#{bin}/p11-kit", "list-modules" end end
require 'date' class Task < Post def initialize super @due_date = Time.now end def read_from_console puts "Введите задачу, затем \"end\", чтобы завершить" @text = STDIN.gets.chomp puts "К какому числу сделать? Введите ответ в формате ДД.ММ.ГГГГ" begin date = STDIN.gets.chomp @due_date = Date.parse(date) rescue ArgumentError abort "ОШИБКА: неверный формат даты" end end def to_strings time_string = "Создано: #{@created_at.strftime("%Y-%m-%d, %H-%M-%S")} \n\n" deadline = "Крайний срок: #{@due_date}" return [deadline, @text, time_string] end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe WorkTimePolicy, type: :policy do let(:user) { User.new } subject { described_class } permissions '.scope' do let(:user) { create(:user) } let(:admin) { create(:user, :admin) } let(:manager) { create(:user, :manager) } context 'admin or mananger' do it 'resolves to all' do create(:work_time) expect(described_class::Scope.new(admin, WorkTime.all).resolve).to match_array WorkTime.all expect(described_class::Scope.new(manager, WorkTime.all).resolve).to match_array WorkTime.all end end context 'normal user' do it "resolves to user's work_times and work_times from leaded projects" do project = create(:project, leader: user) user_work_time = create(:work_time, user: user) project_work_time = create(:work_time, project: project) expect(described_class::Scope.new(user, WorkTime.all).resolve).to match_array [user_work_time, project_work_time] end end end end
require 'rails_helper' RSpec.describe 'the list show page', type: :feature do before :each do worthless_tag = Tag.create(title: 'Worthless Tag') list = List.create(title: 'Bad List', archived: false) task = Task.create(title: 'Bad Task', status: false, description: 'This task is terrible', due_date: Date.new(2017, 1, 1)) tag = Tag.create(title: 'Bad Tag') task.tags << tag list.tasks << task end xit 'displays task attributes' do visit '/' click_link_or_button 'Bad List' click_link_or_button 'Bad Task' expect(page).to have_content('Bad Task') expect(page).to have_content('This task is terrible') end xit 'displays task tags' do visit '/' click_link_or_button 'Bad List' click_link_or_button 'Bad Task' expect(page).to have_content('Bad Tag') end end
module SiegeSiege class Result def initialize(command, urls, raw, raw_result) @command = command @raw = raw @raw_result = raw_result offset = 0 @url_map = urls.each_with_index.inject({}) do |a, (url, index)| a.merge!((index + offset) => url).tap do # if the http method is POST, skip one step (why?) offset += 1 if url.post? end end end def total_result { command: @command }.merge!( @raw_result.split("\n").inject({}) { |a, line| if line.include?('unable to create log file') a elsif re = line.match(/(.+?):[^0-9]*([0-9\.]+) ?(.*)/) a.merge!(re[1].gsub(' ', '_').underscore.to_sym => { value: re[2].to_f, unit: re[3].to_s }) else a end } ) end def raw_log @stored_logs ||= begin @raw .gsub(/\e.+?m/, '') .gsub('[', '') .gsub(']', '') .split("\n") .map { |line| LineLog.new(*line.split(',')).take_in_detail(@url_map) rescue nil } .compact end end def average_log @stored_average_log ||= raw_log.group_by { |line| line.id }.map { |id, group| count = group.size average = (group.inject(0) { |a, log| a + log.secs } / count).round(3) head = group.first AverageLog.new(id, head.url, count, average, head.siege_url) } end end end
module RequestsHelper def request_acceptance_status(request) if request.accepted? == false "<i class='glyphicon glyphicon-remove'></i>".html_safe elsif request.accepted? == true "<i class='glyphicon glyphicon-ok'></i>".html_safe elsif request.expired? 'Ανενεργό' else t('panel.pending') end end def orders_chart_data(user, timeframe) (timeframe.to_date..Date.today).map do |date| { created_at: date, requests: user.requests.where("date(created_at) = ?", date).count } end end def requests_for(user) requests = user.requests r = "<span class='received'>#{t('tutors.received')} #{requests.size}</span> | <span class='ignored'>#{t('tutors.ignored')} #{requests.ignored.size}</span>" return r.html_safe end end
require 'dmtd_vbmapp_data/request_helpers' module DmtdVbmappData # Provides for the retrieving of VB-MAPP Area Question Skill on the VB-MAPP Data Server. class ProtocolAreaSkill # @!attribute [r] id # @return [Symbol] the Skill Id attr_reader :id # @!attribute [r] supporting # @return [Bool] whether the skill is a supporting skill attr_reader :supporting # @!attribute [r] skill # @return [String] the description of the skill attr_reader :skill # Creates an accessor for the VB-MAPP Area Question Skill on the VB-MAPP Data Server # # @note This method does *not* block, simply creates an accessor and returns # # @option opts [Hash] :question_json The vbmapp question json for the question in the format described at # {https://datamtd.atlassian.net/wiki/pages/viewpage.action?pageId=18710549 /1/protocol/area_question - GET REST api - Fields} def initialize(opts) question_json = opts.fetch(:question_json) @id = question_json[:id] @supporting = question_json[:supporting] @skill = question_json[:skill] end end end
module DeviseHelper def devise_error_messages! return "" if resource.errors.empty? messages = resource.errors.full_messages.map {|msg| content_tag(:li, msg)}.join sentence = I18n.t("error.message.not_saved", :count => resource.errors.count, :resource => resource_name) html = <<-HTML <div id="error_explanation"> <ul style="color: #b80000;">#{messages} <li>Please try again</li> </ul> </div> HTML html.html_safe end end
require 're_captcha/rails/helpers' module ReCaptcha class Engine < ::Rails::Engine initializer 're_captcha.action_controller.helpers' do ActiveSupport.on_load(:action_controller) do include ReCaptcha::Rails::Helpers end end initializer 're_captcha.action_view.helpers' do ActiveSupport.on_load(:action_view) do include ReCaptcha::Helpers end end end end
class BankAccount < ActiveRecord::Base belongs_to :member attr_accessible :account_holder, :account_number, :bank_name, :bank_code, :member_id validates :bank_code, :length => { :is => 8 } validates :account_holder, :account_number, :bank_name, :bank_code, :member_id, presence: true validates :bank_code, :numericality => { :only_integer => true } end
class CreateBroSales < ActiveRecord::Migration def change create_table :bro_sales do |t| t.string :name t.text :content t.string :banner t.string :logo t.string :newsletter_list_id t.datetime :deadline t.datetime :shipping_eta t.string :meta_title t.string :slug, unique: true t.boolean :active, default: true, null: false t.boolean :visible, default: true, null: false t.timestamps null: false end add_index :bro_sales, :slug end end
class ContactsController < ApplicationController load_and_authorize_resource before_action :set_contact, only: [:show, :edit, :update, :destroy] after_action :set_birth_month, only: [:create, :update] def index @q = Contact.search(params[:q]) @contacts = @q.result.order('authenticated ASC, id DESC').includes(:participated_groups).paginate(:page => params[:page], :per_page => 50) respond_to do |format| format.json format.html # /app/views/contacts/index.html.erb format.html.phone # /app/views/contacts/index.html+phone.erb format.html.pad # /app/views/contacts/index.html+pad.erb end end def show end def new @contact = Contact.new @my_ip = my_ip end def create if 1 == params[:contact][:unknown_year] params[:contact]["birthday(1i)"]=1900.to_s end if 1 == params[:contact][:unknown_birthday] params[:contact]["birthday(1i)"]=1900.to_s params[:contact]["birthday(2i)"]=1.to_s params[:contact]["birthday(3i)"]=1.to_s end @contact = Contact.new(contact_params) @contact.user = current_user unless current_user.nil? @contact.save ? (redirect_to contacts_path) : (render :new) end def edit @groups = Group.all end def update @contact.updaters << current_user unless @contact.updaters.include? current_user if params[:contact][:'birthday(1i)'] == 1900.to_s params[:contact][:unknown_year] = '1' else params[:contact][:unknown_year] = '0' end if params[:contact][:'birthday(1i)'] == 1900.to_s && params[:contact][:'birthday(2i)'] == 1.to_s && params[:contact][:'birthday(3i)'] == 1.to_s params[:contact][:unknown_birthday] = '1' else params[:contact][:unknown_birthday] = '0' end @contact.update(contact_params) ? (redirect_to contacts_path) : (render :edit) end def destroy @contact.destroy redirect_to contacts_path end def update_month #http://guides.rubyonrails.org/active_record_querying.html#retrieving-multiple-objects Contact.find_each(batch_size: 100) do |c| if c.unknown_birthday c.update_attribute(:birth_month, 0) elsif !c.birthday.nil? c.update_attribute(:birth_month, c.birthday.month) end end redirect_to contacts_path end # massively import records def import user_info = {:current_user=> current_user, :ip=>my_ip} begin file = params[:file] raise '请选择一个要上传的文件!' unless file.respond_to?(:original_filename) file_ext = File.extname(file.original_filename) ci = ContactImporter.new(file.path, extension: file_ext.to_sym, params: user_info) import_result=ci.import if ci.row_errors.length == 0 and ci.error_msg.empty? flash[:notice]= "祝贺你,所有数据都成功导入了!<br>请在联系人列表中逐个编辑用红色背景标记的联系人。<br>检查无误后,请在“审核”一栏打勾,并提交修改。" else flash[:error]= ci.error_msg end rescue => e flash[:error]= e.message #raise ensure @contacts = Contact.readonly.where(user: current_user, updated_at: 30.seconds.ago..Time.now ).order('updated_at DESC') end end private # Use callbacks to share common setup or constraints between actions. def set_contact @contact = Contact.find(params[:id]) end def set_birth_month if @contact.unknown_birthday @contact.birth_month=0 @contact.save! elsif !@contact.birthday.nil? @contact.birth_month=@contact.birthday.month @contact.save! end end def contact_params params.require(:contact).permit( :name, :gender, :telephone, :mobile, :email, :wechat, :address, :birthday, :unknown_year, :unknown_birthday, :birth_month, :come, :decision, :decision_with, :baptism, :go, :created_at, :comment, :job, :find_us, :find_us_additional, :friend_id, :pray, :native_place, :spouse, :authenticated, :register_ip, :q => [], :participated_group_ids => [], :participated_gathering_ids => [] ) end end
class GlAccount < ActiveRecord::Base belongs_to :agency belongs_to :fund, inverse_of: :gl_accounts has_many :class_sessions has_many :facilities has_many :memberships has_many :registrations, :through => :class_sessions validates :agency_id, :fund_id, :name, :gl_account_number, :active, :user_stamp, :account_type, :presence => true validates_uniqueness_of :account_type, :scope => :fund_id, :if => :unique_account_type attr_accessible :agency_id, :fund_id, :name, :gl_account_number, :active, :user_stamp, :account_type # --GL Account Types-- # Bank Charges 1 # Program Revenue 2 # Customer Account Balances 3 # Deferred Revenue 4 # Extra Fee Revenue 5 # Cash 6 # Credit Card 7 # Refund Pending 8 # Tax 9 # Membership Revenue 10 def unique_account_type [3,4,6,7,8].include? account_type end def number_name "#{gl_account_number} - #{name}" end end
# frozen_string_literal: true require 'test_helper' class MeetingsControllerTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers setup do @meeting = meetings(:one) end test 'should get index when signed in' do sign_in users(:one) get meetings_url assert_response :success end test 'should redirect get when not signed in' do get meetings_url assert_redirected_to new_user_session_url end test 'should get new when signed in' do sign_in users(:one) get new_meeting_url assert_response :success end test 'should redirect new when not signed in' do get new_meeting_url assert_redirected_to new_user_session_url end test 'should create meeting when signed in' do sign_in users(:one) assert_difference('Meeting.count') do post meetings_url, params: { meeting: { end_time: @meeting.end_time, name: @meeting.name, start_time: @meeting.start_time, user_id: @meeting.user_id } } end assert_redirected_to meeting_url(Meeting.last) end test 'should not create meeting when not signed in' do assert_no_difference('Meeting.count') do post meetings_url, params: { meeting: { end_time: @meeting.end_time, name: @meeting.name, start_time: @meeting.start_time, user_id: @meeting.user_id } } end assert_redirected_to new_user_session_url end test 'should not show meeting when signed in' do sign_in users(:one) get meeting_url(:en, @meeting) assert_response :error end test 'should reddirect show meeting when not signed in' do get meeting_url(:en, @meeting) assert_redirected_to new_user_session_url end test 'should get edit when user signed in' do sign_in users(:one) get edit_meeting_url(:en, @meeting) assert_response :success end test 'should redirect get edit when user not signed in' do get edit_meeting_url(:en, @meeting) assert_redirected_to new_user_session_url end test 'should update meeting when user signed in' do sign_in users(:one) patch meeting_url(:en, @meeting), params: { meeting: { end_time: @meeting.end_time, name: @meeting.name, start_time: @meeting.start_time, user_id: @meeting.user_id } } assert_response :success end test 'should redirect update meeting when user not signed in' do patch meeting_url(:en, @meeting), params: { meeting: { end_time: @meeting.end_time, name: @meeting.name, start_time: @meeting.start_time, user_id: @meeting.user_id } } assert_redirected_to new_user_session_url end test 'should destroy meeting when user signed in' do sign_in users(:one) assert_difference('Meeting.count', -1) do delete meeting_url(:en, @meeting) end assert_redirected_to meetings_url end test 'should redirect destroy meeting when user not signed in' do assert_no_difference('Meeting.count') do delete meeting_url(:en, @meeting) end assert_redirected_to new_user_session_url end end
class DropQualityUser < ActiveRecord::Migration[6.0] def change remove_column :characters, :qualities end end
require 'rubygems' require 'rake' require 'jeweler' Jeweler::Tasks.new do |gem| # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options gem.name = "pcapr-local" gem.homepage = "http://github.com/pcapr-local/pcapr-local" gem.license = "MIT" gem.summary = %Q{Manage your pcap collection} gem.description = %Q{Index, Browse, and Query your vast pcap collection.} gem.email = "nbaggott@gmail.com" gem.authors = ["Mu Dynamics"] gem.add_dependency "rest-client", ">= 1.6.1" gem.add_dependency "couchrest", "~> 1.0.1" gem.add_dependency "sinatra", "~> 1.1.0" gem.add_dependency "json", ">= 1.4.6" gem.add_dependency "thin", "~> 1.2.7" gem.add_dependency "rack", "~> 1.2.1" gem.add_dependency "rack-contrib", "~> 1.1.0" # Include your dependencies below. Runtime dependencies are required when using your gem, # and development dependencies are only needed for development (ie running rake tasks, tests, etc) # gem.add_runtime_dependency 'jabber4r', '> 0.1' # gem.add_development_dependency 'rspec', '> 1.2.3' gem.add_development_dependency "shoulda", ">= 0" gem.add_development_dependency "bundler", "~> 1.0.0" gem.add_development_dependency "jeweler", "~> 1.5.2" gem.add_development_dependency "rcov", ">= 0" end Jeweler::RubygemsDotOrgTasks.new require 'rake/testtask' Rake::TestTask.new(:test) do |test| test.libs << 'lib' << 'test' test.pattern = 'test/**/test_*.rb' test.verbose = true end require 'rcov/rcovtask' Rcov::RcovTask.new(:rcov) do |test| test.libs << 'test' test.pattern = 'test/**/test_*.rb' test.verbose = true end task :default => :test require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "pcapr-local #{version}" rdoc.rdoc_files.include('README*') end
# # Cookbook Name:: iptables # Recipe:: default # if ['solo', 'app', 'util', 'app_master', 'db_master', 'db_slave'].include?(node[:instance_role]) include_recipe "iptables::install" include_recipe "iptables::config" # Start the iptables service service "iptables" do supports :restart => true action [:enable, :start] end end
require 'spec_helper' def url '/' end feature 'RangeInput' do before(:each) do visit url end let(:range) { find '#range-1' } let(:point) { first '.point' } let(:tick) { first '.tick' } feature 'Smoke test' do scenario 'visit the page' do expect(page.title).to eq 'range' end end feature 'drag and drop' do scenario 'drag left' do value = range.value point.drag_to tick expect(range.value).to be < value end scenario 'drag right' do tickk = all('.tick').last value = range.value # TODO:drag n pixels instead point.drag_to tickk expect(range.value).to be > value end end feature 'keys' do scenario 'press right' do value = range.value point.click point.native.send_keys :arrow_right expect(range.value).to be > value end scenario 'press left' do value = range.value point.click point.native.send_keys :arrow_left expect(range.value).to be < value end scenario 'press up' do value = range.value point.click point.native.send_keys :arrow_up expect(range.value).to be > value end scenario 'press down' do value = range.value point.click point.native.send_keys :arrow_down expect(range.value).to be < value end scenario 'press tab' do replacement = first '.range-replacement' replacement.click replacement.native.send_keys :tab range2 = find('#range-2') focused = page.driver.browser.switch_to.active_element expect(focused).to eq range2.native end end feature 'click' do scenario 'click track changes value' do value = range.value tick.click expect(range.value).to_not be value end end feature 'events' do feature 'focus' feature 'blur' feature 'mousedown' feature 'mouseup' feature 'click' feature 'keydown' feature 'keyup' end feature 'max value' do # Init range with args, try to set > max scenario 'is 17' end feature 'min value' do # Init range with args, try to set < min scenario 'is 4' end feature 'step' do scenario 'is 3, min 0, max 12' end end
require "rails_helper" require "rails_helper" describe VelocitasCore::GpxDownloader do subject { described_class.new(url: url) } let(:url) { "http://www.foo.com/me.gpx" } let(:context) { subject.context } describe "#download" do it "downloads a GPX file" do mock_response = double(body: "<trk></trk>", status: 200) expect_any_instance_of(Faraday::Connection).to receive(:get).with(url).and_return(mock_response) subject.call end it "returns in the context a File reference to where a file was saved" do mock_response = double(body: "<trk></trk>", status: 200) expect_any_instance_of(Faraday::Connection).to receive(:get).with(url).and_return(mock_response) subject.call expect(context.file).to be_instance_of File end context "with supplied filename" do subject { described_class.new(url: url, filename: "foo.gpx") } it "saves the file with supplied filename" do mock_response = double(body: "<trk></trk>", status: 200) expect_any_instance_of(Faraday::Connection).to receive(:get).with(url).and_return(mock_response) subject.call expect(context.file.path).to include "foo.gpx" end end end describe "#success?" do it "returns true if the response returned with an OK status" do mock_response = double(body: "<trk></trk>", status: 200) expect_any_instance_of(Faraday::Connection).to receive(:get).with(url).and_return(mock_response) subject.call expect(subject).to be_success end it "returns false if the response came back with an error" do mock_response = double(body: "<trk></trk>", status: 404) expect_any_instance_of(Faraday::Connection).to receive(:get).with(url).and_return(mock_response) expect { subject.call }.to raise_error(Interactor::Failure) expect(subject).to_not be_success end end end
# encoding: utf-8 require "logstash/devutils/rspec/spec_helper" require "logstash/filters/csv" describe LogStash::Filters::CSV do subject(:plugin) { LogStash::Filters::CSV.new(config) } let(:config) { Hash.new } let(:doc) { "" } let(:event) { LogStash::Event.new("message" => doc) } describe "registration" do context "when using invalid data types" do let(:config) do { "convert" => { "custom1" => "integer", "custom3" => "wrong_type" }, "columns" => ["custom1", "custom2", "custom3"] } end it "should register" do input = LogStash::Plugin.lookup("filter", "csv").new(config) expect {input.register}.to raise_error(LogStash::ConfigurationError) end end end describe "receive" do before(:each) do plugin.register end describe "all defaults" do let(:config) { Hash.new } let(:doc) { "big,bird,sesame street" } it "extract all the values" do plugin.filter(event) expect(event.get("column1")).to eq("big") expect(event.get("column2")).to eq("bird") expect(event.get("column3")).to eq("sesame street") end it "should not mutate the source field" do plugin.filter(event) expect(event.get("message")).to be_kind_of(String) end end describe "empty message" do let(:doc) { "" } let(:config) do { "skip_empty_rows" => true } end it "skips empty rows" do plugin.filter(event) expect(event.get("tags")).to include("_csvskippedemptyfield") expect(event).not_to be_cancelled end end describe "custom separator" do let(:doc) { "big,bird;sesame street" } let(:config) do { "separator" => ";" } end it "extract all the values" do plugin.filter(event) expect(event.get("column1")).to eq("big,bird") expect(event.get("column2")).to eq("sesame street") end end describe "quote char" do let(:doc) { "big,bird,'sesame street'" } let(:config) do { "quote_char" => "'"} end it "extract all the values" do plugin.filter(event) expect(event.get("column1")).to eq("big") expect(event.get("column2")).to eq("bird") expect(event.get("column3")).to eq("sesame street") end context "using the default one" do let(:doc) { 'big,bird,"sesame, street"' } let(:config) { Hash.new } it "extract all the values" do plugin.filter(event) expect(event.get("column1")).to eq("big") expect(event.get("column2")).to eq("bird") expect(event.get("column3")).to eq("sesame, street") end end context "using a null" do let(:doc) { 'big,bird,"sesame" street' } let(:config) do { "quote_char" => "\x00" } end it "extract all the values" do plugin.filter(event) expect(event.get("column1")).to eq("big") expect(event.get("column2")).to eq("bird") expect(event.get("column3")).to eq('"sesame" street') end end context "using a null as read from config" do let(:doc) { 'big,bird,"sesame" street' } let(:config) do { "quote_char" => "\\x00" } end it "extract all the values" do plugin.filter(event) expect(event.get("column1")).to eq("big") expect(event.get("column2")).to eq("bird") expect(event.get("column3")).to eq('"sesame" street') end end end describe "given column names" do let(:doc) { "big,bird,sesame street" } let(:config) do { "columns" => ["first", "last", "address" ] } end it "extract all the values" do plugin.filter(event) expect(event.get("first")).to eq("big") expect(event.get("last")).to eq("bird") expect(event.get("address")).to eq("sesame street") end context "parse csv without autogeneration of names" do let(:doc) { "val1,val2,val3" } let(:config) do { "autogenerate_column_names" => false, "columns" => ["custom1", "custom2"] } end it "extract all the values" do plugin.filter(event) expect(event.get("custom1")).to eq("val1") expect(event.get("custom2")).to eq("val2") expect(event.get("column3")).to be_falsey end end context "parse csv and skip the header" do let(:doc) { "first_column,second_column,third_column" } let(:config) do { "skip_header" => true, "columns" => ["first_column", "second_column", "third_column"] } end it "expects the event to be cancelled" do plugin.filter(event) expect(event).to be_cancelled end end context "parse csv skipping empty columns" do let(:doc) { "val1,,val3" } let(:config) do { "skip_empty_columns" => true, "source" => "datafield", "columns" => ["custom1", "custom2", "custom3"] } end let(:event) { LogStash::Event.new("datafield" => doc) } it "extract all the values" do plugin.filter(event) expect(event.get("custom1")).to eq("val1") expect(event.get("custom2")).to be_falsey expect(event.get("custom3")).to eq("val3") end end context "parse csv with more data than defined" do let(:doc) { "val1,val2,val3" } let(:config) do { "columns" => ["custom1", "custom2"] } end it "extract all the values" do plugin.filter(event) expect(event.get("custom1")).to eq("val1") expect(event.get("custom2")).to eq("val2") expect(event.get("column3")).to eq("val3") end end context "parse csv from a given source" do let(:doc) { "val1,val2,val3" } let(:config) do { "source" => "datafield", "columns" => ["custom1", "custom2", "custom3"] } end let(:event) { LogStash::Event.new("datafield" => doc) } it "extract all the values" do plugin.filter(event) expect(event.get("custom1")).to eq("val1") expect(event.get("custom2")).to eq("val2") expect(event.get("custom3")).to eq("val3") end end context "that use [@metadata]" do let(:metadata_field) { "[@metadata][one]" } let(:config) do { "columns" => [ metadata_field, "foo" ] } end let(:event) { LogStash::Event.new("message" => "hello,world") } before do plugin.filter(event) end it "should work correctly" do expect(event.get(metadata_field)).to eq("hello") end end end describe "givin target" do let(:config) do { "target" => "data" } end let(:doc) { "big,bird,sesame street" } let(:event) { LogStash::Event.new("message" => doc) } it "extract all the values" do plugin.filter(event) expect(event.get("data")["column1"]).to eq("big") expect(event.get("data")["column2"]).to eq("bird") expect(event.get("data")["column3"]).to eq("sesame street") end context "when having also source" do let(:config) do { "source" => "datain", "target" => "data" } end let(:event) { LogStash::Event.new("datain" => doc) } let(:doc) { "big,bird,sesame street" } it "extract all the values" do plugin.filter(event) expect(event.get("data")["column1"]).to eq("big") expect(event.get("data")["column2"]).to eq("bird") expect(event.get("data")["column3"]).to eq("sesame street") end end context "which uses [nested][fieldref] syntax" do let(:target) { "[foo][bar]" } let(:config) do { "target" => target } end let(:event) { LogStash::Event.new("message" => "hello,world") } before do plugin.filter(event) end it "should set fields correctly in the target" do expect(event.get("#{target}[column1]")).to eq("hello") expect(event.get("#{target}[column2]")).to eq("world") end context "with nested fieldrefs as columns" do let(:config) do { "target" => target, "columns" => [ "[test][one]", "[test][two]" ] } end it "should set fields correctly in the target" do expect(event.get("#{target}[test][one]")).to eq("hello") expect(event.get("#{target}[test][two]")).to eq("world") end end end end describe "using field convertion" do let(:config) do { "convert" => { "column1" => "integer", "column3" => "boolean", "column4" => "float", "column5" => "date", "column6" => "date_time", "column7" => "date", "column8" => "date_time", } } end # 2017-06-01,2001-02-03T04:05:06+07:00 let(:doc) { "1234,bird,false,3.14159265359,2017-06-01,2001-02-03 04:05:06,invalid_date,invalid_date_time" } let(:event) { LogStash::Event.new("message" => doc) } it "converts to integer" do plugin.filter(event) expect(event.get("column1")).to eq(1234) end it "does not convert without converter" do plugin.filter(event) expect(event.get("column2")).to eq("bird") end it "converts to boolean" do plugin.filter(event) expect(event.get("column3")).to eq(false) end it "converts to float" do plugin.filter(event) expect(event.get("column4")).to eq(3.14159265359) end it "converts to date" do plugin.filter(event) expect(event.get("column5")).to be_a(LogStash::Timestamp) expect(event.get("column5").to_s).to eq(LogStash::Timestamp.new(Date.parse("2017-06-01").to_time).to_s) end it "converts to date_time" do plugin.filter(event) expect(event.get("column6")).to be_a(LogStash::Timestamp) expect(event.get("column6").to_s).to eq(LogStash::Timestamp.new(DateTime.parse("2001-02-03 04:05:06").to_time).to_s) end it "tries to converts to date but return original" do plugin.filter(event) expect(event.get("column7")).to eq("invalid_date") end it "tries to converts to date_time but return original" do plugin.filter(event) expect(event.get("column8")).to eq("invalid_date_time") end context "when using column names" do let(:config) do { "convert" => { "custom1" => "integer", "custom3" => "boolean" }, "columns" => ["custom1", "custom2", "custom3"] } end it "get converted values to the expected type" do plugin.filter(event) expect(event.get("custom1")).to eq(1234) expect(event.get("custom2")).to eq("bird") expect(event.get("custom3")).to eq(false) end end end describe "given autodetect option" do let(:header) { LogStash::Event.new("message" => "first,last,address") } let(:doc) { "big,bird,sesame street" } let(:config) do { "autodetect_column_names" => true } end it "extract all the values with the autodetected header" do plugin.filter(header) plugin.filter(event) expect(event.get("first")).to eq("big") expect(event.get("last")).to eq("bird") expect(event.get("address")).to eq("sesame street") end end end end
require "./test/test_helper" class TestRubotRequestsBuilder < Test::Unit::TestCase module Rubot::RequestsBuilder::Action1 def self.valid?(*) false end def self.build_requests(message) 'action1' end end module Rubot::RequestsBuilder::Action2 def self.valid?(*) true end def self.build_requests(message) 'action2' end end module Rubot::RequestsBuilder::MissingMethodValidAction def self.build_requests(message) 'action2' end end module Rubot::RequestsBuilder::MissingMethodBuildRequests def self.valid?(*) true end end teardown do Rubot::RequestsBuilder.clear! end test 'configure no strategies' do assert_empty Rubot::RequestsBuilder.request_builders end test 'configure a valid strategy' do assert_not_empty Rubot::RequestsBuilder.config([Rubot::RequestsBuilder::Action1]) end test "raise error if I add a strategy that does not have an valid? method" do assert_raise NoMethodError do Rubot::RequestsBuilder.config([Rubot::RequestsBuilder::MissingMethodValidAction]) end end test "raise error if I add a strategy that does not have an build_requests method" do assert_raise NoMethodError do Rubot::RequestsBuilder.config([Rubot::RequestsBuilder::MissingMethodBuildRequests]) end end test "return result of a correct requests builder" do Rubot::RequestsBuilder.config([Rubot::RequestsBuilder::Action2]) assert_equal('action2', Rubot::RequestsBuilder.get_request(nil)) end test "return nil if there is no correct requests builder" do Rubot::RequestsBuilder.config([Rubot::RequestsBuilder::Action1]) assert_empty Rubot::RequestsBuilder.get_request(nil) end end
# Copyright © 2011-2019 MUSC Foundation for Research Development~ # All rights reserved.~ # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~ # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~ # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~ # disclaimer in the documentation and/or other materials provided with the distribution.~ # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~ # derived from this software without specific prior written permission.~ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~ # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~ # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~ require 'rails_helper' RSpec.describe 'dashboard/sub_service_requests/_header', type: :view do include RSpecHtmlMatchers before(:each) do allow(view).to receive(:user_display_protocol_total).and_return(100) end describe "status dropdown" do it "should be populated with statuses from associated Organization" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, submitted: true) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive(:unread_notification_count). with(sub_service_request.id).and_return("12345") stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("select#sub_service_request_status") do with_option("Draft") with_option("Invoiced") end end context 'SubServiceRequest has been previously submitted' do it 'should disable the dropdown' do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, submitted: false) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive(:unread_notification_count). with(sub_service_request.id).and_return("12345") stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_selector('select#sub_service_request_status[disabled=disabled]') end end end describe "owner dropdown" do context "SubServiceRequest in draft status" do it "should not be displayed" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, status: "draft") logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive(:unread_notification_count). with(sub_service_request.id).and_return("12345") stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).not_to have_tag("select#sub_service_request_owner") end end context "SubServiceRequest not in draft status" do it "should be populated with candidate owners for SubServiceRequest" do protocol = stub_protocol organization = stub_organization sub_service_request_owner = build_stubbed(:identity, first_name: "Thing", last_name: "1") potential_owner = build_stubbed(:identity, first_name: "Thing", last_name: "2") sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, status: "not_draft", candidate_owners: [sub_service_request_owner, potential_owner]) allow(sub_service_request).to receive(:owner_id). and_return(sub_service_request_owner.id) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive(:unread_notification_count). with(sub_service_request).and_return("12345") stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("select#sub_service_request_owner") do with_option("Thing 1") with_option("Thing 2") end end end end describe "fulfillment button" do context "SubServiceRequest ready for fulfillment" do context "and in fulfillment" do context "user has go to cwf rights" do context "ssr has been imported to fulfillment" do it "should display the 'Go to Fulfillment' button, linking to CWF" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, status: "draft") allow(sub_service_request).to receive_messages(ready_for_fulfillment?: true, in_work_fulfillment?: true, imported_to_fulfillment?: true) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive_messages(unread_notification_count: 12345, go_to_cwf_rights?: true) stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("a", text: "Go to Fulfillment", with: { href: "#{Setting.get_value("clinical_work_fulfillment_url")}/sub_service_request/#{sub_service_request.id}" }) end end context "ssr has not yet been imported to fulfillment" do it "should display the 'Pending' button" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, status: "draft") allow(sub_service_request).to receive_messages(ready_for_fulfillment?: true, in_work_fulfillment?: true, imported_to_fulfillment?: false) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive_messages(unread_notification_count: 12345, go_to_cwf_rights?: true) stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("button", text: "Pending", with: {disabled: "disabled"}) end end end context "user does not have go to fulfillment rights" do it "should display the 'In Fulfillment' button, linking to CWF" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, status: "draft") allow(sub_service_request).to receive_messages(ready_for_fulfillment?: true, in_work_fulfillment?: true) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive_messages(unread_notification_count: 12345, go_to_cwf_rights?: false) stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("button", text: "In Fulfillment", with: {disabled: "disabled"}) end end end context "and not in fulfillment" do context "user has send to cwf rights" do it "should display the 'Send to FulFillment' button" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, status: "draft") allow(sub_service_request).to receive_messages(ready_for_fulfillment?: true, in_work_fulfillment?: false) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive_messages(unread_notification_count: 12345, send_to_cwf_rights?: true) stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("button", text: "Send to Fulfillment") end end context "user does not have send to cwf rights" do it "should display the disabled 'Send to FulFillment' button" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, status: "draft") allow(sub_service_request).to receive_messages(ready_for_fulfillment?: true, in_work_fulfillment?: false) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive_messages(unread_notification_count: 12345, send_to_cwf_rights?: false) stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("button", text: "Send to Fulfillment", with: {disabled: "disabled"}) end end end end context "SubServiceRequest not ready for fulfillment" do it "should display a message indicating that the SSR is not ready" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization, status: "draft") allow(sub_service_request).to receive_messages(ready_for_fulfillment?: false) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive_messages(unread_notification_count: 12345) stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("span", text: "Not enabled in SPARCCatalog.") end end end it "should display the current cost" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive(:unread_notification_count). with(sub_service_request).and_return("12345") stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("td.effective_cost", text: /\$543\.21/) end it "should display the user display cost" do protocol = stub_protocol organization = stub_organization sub_service_request = stub_sub_service_request(protocol: protocol, organization: organization) logged_in_user = build_stubbed(:identity) allow(logged_in_user).to receive(:unread_notification_count). with(sub_service_request).and_return("12345") stub_current_user(logged_in_user) allow(sub_service_request).to receive(:notes).and_return(["1"]) allow(sub_service_request).to receive(:is_complete?).and_return(false) render "dashboard/sub_service_requests/header", sub_service_request: sub_service_request expect(response).to have_tag("td.display_cost", text: /\$100\.00/) end def stub_protocol build_stubbed(:protocol, short_title: "MyAwesomeProtocol") end # specify protocol and organization def stub_sub_service_request(opts = {}) d = instance_double(SubServiceRequest, id: 1, protocol: opts[:protocol], organization: opts[:organization], ssr_id: "0001", status: opts[:status] || "NotDraft", # default "NotDraft" candidate_owners: opts[:candidate_owners] || [], # default [] imported_to_fulfillment?: opts[:imported_to_fulfillment?].nil? || opts[:imported_to_fulfillment?], # default true ready_for_fulfillment?: opts[:ready_for_fulfillment?].nil? || opts[:ready_for_fulfillment?], # default true in_work_fulfillment?: opts[:in_work_fulfillment?].nil? || opts[:in_work_fulfillment?]) # default true # TODO refactor pricing, cost calculations effective_cost = 54321 displayed_cost = 54320 expect(d).to receive(:previously_submitted?) do allow(d).to receive(:previously_submitted?).and_return(opts[:submitted]) end expect(d).to receive(:set_effective_date_for_cost_calculations) do allow(d).to receive(:direct_cost_total).and_return(effective_cost) end allow(d).to receive(:direct_cost_total).and_return(displayed_cost) expect(d).to receive(:unset_effective_date_for_cost_calculations) do allow(d).to receive(:direct_cost_total).and_return(displayed_cost) end allow(d).to receive(:service_request) d end def stub_organization(opts = {}) default_statuses = { "draft" => "Draft", "invoiced" => "Invoiced" } instance_double(Organization, name: "MegaCorp", abbreviation: "MC", get_available_statuses: opts[:get_available_statuses].nil? ? default_statuses : opts[:get_available_statuses]) end def stub_current_user(user) ActionView::Base.send(:define_method, :current_user) { user } end end
# frozen_string_literal: true shared_examples_for 'globus::config' do |_facts| let(:endpoint_setup) do [ 'globus-connect-server endpoint setup', "'Example' --client-id foo --secret 'bar'", "--owner 'admin@example.com'", "--organization 'Example'", '--deployment-key /var/lib/globus-connect-server/gcs-manager/deployment-key.json', '--agree-to-letsencrypt-tos' ] end let(:node_setup) do [ 'globus-connect-server node setup', '--client-id foo', '--deployment-key /var/lib/globus-connect-server/gcs-manager/deployment-key.json', '--incoming-port-range 50000 51000', '--ip-address 172.16.254.254' ] end it do is_expected.to contain_file('/root/globus-endpoint-setup').with( ensure: 'file', owner: 'root', group: 'root', mode: '0700', show_diff: 'false', content: "export GLOBUS_CLIENT_SECRET=bar #{endpoint_setup.join(' ')} ", ) end it do is_expected.to contain_file('/root/globus-node-setup').with( ensure: 'file', owner: 'root', group: 'root', mode: '0700', show_diff: 'false', content: "export GLOBUS_CLIENT_SECRET=bar #{node_setup.join(' ')} ", ) end it 'has endpoint setup command' do is_expected.to contain_exec('globus-endpoint-setup').with( path: '/usr/bin:/bin:/usr/sbin:/sbin', command: endpoint_setup.join(' '), environment: ['GLOBUS_CLIENT_SECRET=bar'], creates: '/var/lib/globus-connect-server/gcs-manager/deployment-key.json', logoutput: 'true', ) end it 'has node setup command' do is_expected.to contain_exec('globus-node-setup').with( path: '/usr/bin:/bin:/usr/sbin:/sbin', command: node_setup.join(' '), environment: ['GLOBUS_CLIENT_SECRET=bar'], unless: 'test -s /var/lib/globus-connect-server/info.json', logoutput: 'true', require: 'Exec[globus-endpoint-setup]', ) end it { is_expected.not_to contain_firewall('500 allow GridFTP control channel') } it do is_expected.to contain_firewall('500 allow HTTPS').with( action: 'accept', dport: '443', proto: 'tcp', ) end it do is_expected.to contain_firewall('500 allow GridFTP data channels').with( action: 'accept', dport: '50000-51000', proto: 'tcp', ) end context 'when run_setup_commands => false' do let(:params) { default_params.merge(run_setup_commands: false) } it { is_expected.not_to contain_exec('globus-endpoint-setup') } it { is_expected.not_to contain_exec('globus-node-setup') } end context 'when extra_gridftp_settings defined' do let(:params) do default_params.merge(extra_gridftp_settings: [ 'log_level ALL', 'log_single /var/log/gridftp-auth.log', 'log_transfer /var/log/gridftp.log', '$LLGT_LOG_IDENT "gridftp-server-llgt"', '$LCMAPS_DB_FILE "/etc/lcmaps.db"', '$LCMAPS_POLICY_NAME "authorize_only"', '$LLGT_LIFT_PRIVILEGED_PROTECTION "1"', '$LCMAPS_DEBUG_LEVEL "2"' ]) end it do is_expected.to contain_file('/etc/gridftp.d/z-extra-settings').with(ensure: 'file', owner: 'root', group: 'root', mode: '0644', notify: 'Service[globus-gridftp-server]') end it do verify_contents(catalogue, '/etc/gridftp.d/z-extra-settings', [ 'log_level ALL', 'log_single /var/log/gridftp-auth.log', 'log_transfer /var/log/gridftp.log', '$LLGT_LOG_IDENT "gridftp-server-llgt"', '$LCMAPS_DB_FILE "/etc/lcmaps.db"', '$LCMAPS_POLICY_NAME "authorize_only"', '$LLGT_LIFT_PRIVILEGED_PROTECTION "1"', '$LCMAPS_DEBUG_LEVEL "2"' ]) end end context 'when manage_firewall => false' do let(:params) { default_params.merge(manage_firewall: false) } it { is_expected.not_to contain_firewall('500 allow GridFTP control channel') } it { is_expected.not_to contain_firewall('500 allow GridFTP data channels') } it { is_expected.not_to contain_firewall('500 allow HTTPS') } end end
class Shot < ActiveRecord::Base belongs_to :game scope :in_game_order, ->{order(:in_game_id)} end
require 'spec_helper' describe StaticPage do before do @page = StaticPage.create!(valid_attributes_for(:static_page)) end it { should be_versioned } context 'return false on invalid inputs' do it 'blank Title' do @page.title = '' expect(@page.save).to be_false end end it 'should NOT allow friendly IDs to be shared within a project' do page = StaticPage.create(title: @page.title) expect(page.friendly_id).to_not eq @page.friendly_id end context 'return true on correct inputs' do it 'is valid' do expect(@page).to be_valid end end context 'correct urls for static pages' do context 'with ancestors' do before(:each) do @page_child = StaticPage.create!(valid_attributes_for(:static_page).merge(parent_id: @page.id)) @page_url = "#{@page.slug}/#{@page_child.slug}" end it 'returns url for static page object' do expect(StaticPage.url_for_me(@page_child)).to eq @page_url end it 'returns url for static page title' do expect(StaticPage.url_for_me(@page_child.title)).to eq @page_url end it 'returns url for static page slug' do expect(StaticPage.url_for_me(@page_child.slug)).to eq @page_url end end context 'without ancestors' do it 'returns url for static page object' do expect(StaticPage.url_for_me(@page)).to eq @page.slug end it 'returns url for static page title' do expect(StaticPage.url_for_me(@page.title)).to eq @page.slug end it 'returns url for static page slug' do expect(StaticPage.url_for_me(@page.slug)).to eq @page.slug end end it 'returns url for non-existant static page' do expect(StaticPage.url_for_me('does not exist')).to eq 'does-not-exist' end end end
# frozen_string_literal: true Sequel.migration do change do create_table(:sessions) do Integer :session_id foreign_key :event_id, :events primary_key %i[session_id event_id] DateTime :start_time, null: false DateTime :end_time, null: false String :address String :place String :ticket_price DateTime :created_at DateTime :updated_at end end end
DynamicAnnotationFieldType = GraphqlCrudOperations.define_default_type do name 'DynamicAnnotationField' description 'DynamicAnnotation::Field type' interfaces [NodeIdentification.interface] field :annotation, AnnotationType end
module TilesHelper def classify_tile t case t when Tile then t.classify when true then :reservable else :blank end end def is_owner? tile,user tile.is_a?(Tile) && tile.user==user end def self.coordinate_id x,y "#{x}x#{y}" end def coordinate_id x,y TilesHelper.coordinate_id x,y end def render_table tt,layout,page,&b render :partial => "/tiles/tables/#{layout}",:locals => {:table=>tt,:page=>page,:block=>b} end def link_to_tile_on_page(tile,&b) link_to render_table(tile.surroundings,'show_mini',tile.page,&b),page_path(tile.page,:anchor=>coordinate_id(tile.x,tile.y)) end def tilemap_css(w,h) dim=[w,h] name= "tilemap#{w}x#{h}" unless (@csslist||=[]).include?(dim) @csslist << dim render :partial=>'/tiles/tables/tilemap_css',:locals=>{:w=>w,:h=>h,:name=>name} end name end def remaining_time_of tile t=tile.remaining_time "<div class='remaining'>" + if t>0 "noch #{distance_of_time_in_words(t,0,true)}" else "Zeit abgelaufen" end + "</div>" end ##################################### ### haml-tags ##################################### def tile_action_box(tile=nil,&b) haml_tag :table, {:class=>:"action-box"} do if (tile.is_a?(Tile) && (tile.points>0)) haml_tag :tr do haml_tag :td,{:class=>:points} do haml_concat tile.points end end end haml_tag :tr do haml_tag :td,{:class=>:main}, &b end if (tile.is_a?(Tile)) haml_tag :tr do haml_tag :td,{:class=>:owner} do haml_concat user_text_link(tile.user) end end end end end def tile_tag(col,row,tile,show_image =true,style=nil,&b) c=classify_tile(tile) own = tile.user_id==current_user.id rescue nil attrs={:id=>coordinate_id(col,row),:class=>"tile #{c}#{own.nil? ? '' : ' '+ (own ? 'own' : 'foreign')}" } attrs[:style]= "background:url(#{tile.image.url(style)}) no-repeat" if show_image && tile.is_a?(Tile) && tile.image.file? haml_tag :td,attrs,&b end #def render_tile(tile,col,row,page,mode) # c=classify_tile tile # own=is_owner? tile,current_user # render :partial => "/tiles/#{mode}/#{c}", :locals => {:x=>col,:y=>row,:page=>page,:tile=>tile,:own=>own} #end end
# == Schema Information # # Table name: bookmarks # # id :integer not null, primary key # user_id :integer not null # folder_id :integer not null # resource_id :integer not null # order :integer default(0) # created_at :datetime not null # updated_at :datetime not null # class Bookmark < ActiveRecord::Base belongs_to :user belongs_to :folder belongs_to :blog_post belongs_to :event belongs_to :resource, counter_cache:true attr_accessible :user, :folder, :resource, :resource_id, :user_id, :folder_id, :blog_post_id, :event_id, :blog_post, :event delegate :name, :teaser, to: :resource, prefix: true validates :user, :folder, presence: true after_create :fix_counter_cache after_save :fix_counter_cache after_destroy :fix_counter_cache private def fix_counter_cache if self.folder_id_was Folder.find(self.folder_id_was).update_bookmarks_count end self.folder.update_bookmarks_count end class << self def ordered order("bookmarks.created_at DESC") end end end
class ChangeQuotaToQuotas < ActiveRecord::Migration[5.1] def change rename_table :quota, :quotas end end
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] # GET /users # GET /users.json # def index # @users = User.all # @memorycards = MemoryCard.all # end # GET /users/1 # GET /users/1.json def show end # GET /users/new def new @user = User.new end # def homefeed # puts "flash recorded" # if params["user"] != nil and params["user"]["memory"] != nil # flash[:notice] = "memory was successfully created." # session[:recorded_memory] = params["user"]["memory"] # puts flash # end # end # GET /users/1/edit def edit @change = params[:format] end # POST /users # POST /users.json def create if (user_params[:first_name] == "" || user_params[:last_name] == "" || user_params[:username] == "" || user_params[:email] == "" || user_params[:password] == "" || user_params[:password_confirmation] == "") flash[:notice] = 'All fields are required' redirect_to users_signup_path(:user => user_params) else username_check = User.find_by_username(user_params[:username]) email_check = User.find_by_email(user_params[:email]) if (username_check) flash[:notice] = 'Username already exists' redirect_to users_signup_path(:user => user_params) elsif(email_check) flash[:notice] = 'email is associated with an existing user' redirect_to users_signup_path(:user => user_params) elsif (user_params[:password] != user_params[:password_confirmation]) flash[:notice] = 'Password confirmation did not match password' redirect_to users_signup_path(:user => user_params) else @user = User.new(user_params) if @user.save session[:user_id] = @user.id @user.getInitialCards redirect_to '/' else redirect_to users_path end end end end # Get /users/signup def sign_up if (params.key?("user")) @user_params = user_params else redirect_to users_signup_path(:user => {:first_name => "", :last_name => "", :username => "", :email => "", :password => "", :password_confirmation => ""}) end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update respond_to do |format| if (!user_params[:email].nil?) if (current_user.email_already_used(user_params[:email])) flash[:alert] = "Email Already In Use" return redirect_to edit_user_path(current_user, 'email') end end if (!user_params[:password].nil?) if (user_params[:password] != user_params[:password_confirmation]) flash[:alert] = "New Password Not Confirmed" return redirect_to edit_user_path(current_user, 'password') else @user.password = params[:password] end end if @user.update(user_params) flash[:notice] = 'User was successfully updated.' return redirect_to users_settings_path else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json # def destroy # @user.destroy # respond_to do |format| # format.html { redirect_to users_url, notice: 'User was successfully destroyed.' } # format.json { head :no_content } # end # end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:first_name, :last_name, :username, :framework, :email, :password, :password_confirmation) end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :orders, dependent: :destroy validates :first_name, presence: true validates :last_name, presence: true validates :address, presence: true validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, on: :create geocoded_by :address after_validation :geocode, if: :will_save_change_to_address? end
require 'spec_helper' describe CachedHash do subject { CachedHash.new key, ttl} let(:key) { "a key" } let(:ttl) { 10 } let(:content) { {a: 1, b: 2} } context 'when given key has not expired' do before do existing = CachedHash.new key, ttl existing.set content end it 'respects remaining ttl' do subject = CachedHash.new key, 10*ttl subject.should_not be_expired subject.ttl.should <= ttl end end describe '#expired?' do it 'is true when key does not exist' do subject.should be_expired end it 'is false if TTL is larger than given input' do subject.stub :ttl => 10 subject.should_not be_expired end end describe '#set' do it 'sets values to key' do REDIS.should_receive(:hmset).with(key, :blah, 123) subject.set blah: 123 end it 'sets an expirary time' do REDIS.should_receive(:expire).with(key, ttl) subject.set blah:123 end it 'returns values set' do subject.set(blah:123).should == { "blah" => "123" } end end describe '#get' do it 'reads from Redis' do REDIS.should_receive(:hgetall).with(key) subject.get end end end
class AddGoodToCartGoods < ActiveRecord::Migration def change add_reference :cart_goods, :good, index: true end end
class UsersController < ApplicationController before_action :set_profile, only: [:index, :new, :create, :show, :update, :edit, :destroy] before_action :set_user, only: [:edit, :update, :show, :destroy] def index @users = User.all end def new @user = User.new end def create @user = @profile.users.create(user_params) if @user.save created_product = Product.user_pref(@user) Order.create(user_id: @user.id, product_id: created_product.id) rescue nil redirect_to profile_path(@profile), notice: "User was successfully created" else render :new end end def show end def ajax @user = User.find(params[:id]) @profile = Profile.find(params[:profile_id]) if request.xhr? render '_user', layout: false end end def edit @user = User.find(params[:id]) @profile = Profile.find(params[:profile_id]) if request.xhr? render '_new', layout: false end end def update respond_to do |format| if @user.update(user_params) format.html { redirect_to profile_path(@profile), notice: 'User was successfully updated.' } format.json { render :show, status: :ok, location: @user } else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def destroy @user.destroy respond_to do |format| format.html { redirect_to profiles_url, notice: 'User was successfully destroyed.' } format.json { head :no_content } end end private def user_params params.require(:user).permit(:first_name, :last_name, :birthday, :variety, :flow, :scent) end def set_profile @profile = Profile.find(params[:profile_id]) end def set_user @user = User.find(params[:id]) end end
class Cart < ActiveRecord::Base has_many :pledges, dependent: :destroy attr_accessor :amount def add_project(project_id) current_pledge = pledges.find_by(project_id: project_id) if current_pledge current_pledge.interval += 1 #current_pledge.amount += amount.to_i else #current_pledge = pledges.amount current_pledge = pledges.build(project_id: project_id) end current_pledge end def total_estimate #pledges.to_a.sum { |pledge| pledge.total_estimate } pledges.to_a.sum { |pledge| pledge.total_amount } end end
require "pry" require "csv" def process_csv accounts = {} CSV.foreach("accounts.csv", {headers: true, return_headers: false}) do |row| # Add a key for each account to the accounts Hash. account = row["Account"].chomp if !accounts[account] accounts[account] = { tally: 0.00, categories: { } } end # Set the account which is being affected by this iteration. current_account = accounts[account] # Clean up outflow and inflow. outflow = row["Outflow"].gsub(/[,\$]/, "").to_f.round(2) inflow = row["Inflow"].gsub(/[,\$]/, "").to_f.round(2) transaction_amount = inflow - outflow # Keep a tally for current balance of the account. current_account[:tally] += transaction_amount category = row["Category"].chomp # Initialize category. if !current_account[:categories][category] current_account[:categories][category] = { tally: 0.00, num_transactions: 0, average_transaction_cost: 0.00 } end # Tally category. current_account[:categories][category][:tally] += transaction_amount # Increment transaction counter. current_account[:categories][category][:num_transactions] += 1 # Update average transaction cost. current_account[:categories][category][:average_transaction_cost] = current_account[:categories][category][:tally] / current_account[:categories][category][:num_transactions] end return accounts end
require 'prawn_charts/components/component' module PrawnCharts module Components class ValueMarkers < Component DEFAULT_MARKER_FONT_SIZE = 5 include PrawnCharts::Helpers::Marker attr_accessor :markers def draw(pdf, bounds, options={}) pdf.reset_text_marks #pdf.text_mark ":#{id} centroid #{pdf.bounds.left+bounds[:x]+bounds[:width]/2.0,},#{pdf.bounds.bottom+bounds[:y]+bounds[:height]/2.0], :radius => 3}" pdf.centroid_mark([pdf.bounds.left+bounds[:x]+bounds[:width]/2.0,pdf.bounds.bottom+bounds[:y]+bounds[:height]/2.0],:radius => 3) pdf.crop_marks([pdf.bounds.left+bounds[:x],pdf.bounds.bottom+bounds[:y]+bounds[:height]],bounds[:width],bounds[:height]) #pdf.axis_marks markers = (options[:markers] || self.markers) || 5 each_marker(markers, options[:min_value], options[:max_value], bounds[:height], options, :value_formatter) do |label, y| font_family = theme.font_family || "Helvetica" font_size = theme.marker_font_size ? relative(theme.marker_font_size) : relative(DEFAULT_MARKER_FONT_SIZE) text_color = options[:marker_color_override] || theme.marker || '000000' #pdf.text_mark("label #{label}, x #{bounds[:x]+bounds[:width]}, y #{bounds[:y]+y+font_size}, w #{ bounds[:width]}, font_family #{font_family}, font_size #{font_size}, text_color #{text_color} :align => :right") pdf.font(font_family) do pdf.fill_color text_color pdf.text_box options[:title], :at => [pdf.bounds.left+bounds[:x]+bounds[:width],pdf.bounds.bottom+bounds[:y]+y+font_size], :width => bounds[:width], :align => :right, :color => text_color, :size => font_size end end end end # ValueMarkers end # Components end # PrawnCharts
class AdminsController < ApplicationController before_filter :bomb_dot_com before_filter :super_users_only, :except => [:index] def new @title = "Create a new Administrator" @admin = Admin.new end def create @admin = Admin.new( params[:admin] ) if @admin.valid? @admin.save redirect_to admins_path else render "new" end end def index @title = "Administrators" @admins = Admin.special_select end def edit @admin = Admin.find(params[:id]) end def update @admin = Admin.find(params[:id]) if @admin.update_attributes(params[:admin]) redirect_to admins_path, :notice => "Password Changed" else render "edit" end end def destroy if params[:id] == session[:admin_id].to_s redirect_to admins_path, :notice => "You can't delete yourself silly..." else @admin = Admin.find(params[:id]) if @admin.destroy redirect_to admins_path, :notice => "#{@admin.email} has been removed from the admins" else @admins = Admin.special_select render :index end end end private def super_users_only @current_user = Admin.find(session[:admin_id]) unless @current_user.super_user? redirect_to admins_path, :notice => "You do not have rights to this page" end end end
require 'open-uri' require 'nokogiri' class TwitterWurst::Twit attr_accessor :name, :handle, :url, :tweets def initialize(handle, url) doc = Nokogiri::HTML(open"(https://www.twitter.com/#{:handle}") @tweets = [] @name = doc.search("h1.ProfileHeaderCard-name a").text - "Verified account" @handle = handle @url = url end end
ACCESS_TOKEN = "your github access token" require_relative 'sprint_statistics' require 'more_core_extensions/core_ext/array/element_counts' def stats @stats ||= SprintStatistics.new(ACCESS_TOKEN) end def most_recent_monday @most_recent_monday ||= begin time = Time.now.utc.midnight loop do break if time.monday? time -= 1.day end time end end def sprint_range @sprint_range ||= ((most_recent_monday - 2.weeks)..most_recent_monday) end def repos_to_track stats.project_names_from_org("ManageIQ").to_a + ["Ansible/ansible_tower_client_ruby"] end labels = ["bug", "enhancement", "developer", "documentation", "performance", "refactoring", "technical debt", "test", ] results = [] repos_to_track.sort.each do |repo| puts "Collecting pull_requests for: #{repo}" prs = stats.pull_requests(repo, :state => :all, :since => sprint_range.first.iso8601) closed = prs.select { |pr| sprint_range.include?(pr.closed_at) } closed_labels_hash = closed.each_with_object([]) { |pr, arr| pr.labels.each { |label| arr << label.name } }.element_counts opened = prs.select { |pr| sprint_range.include?(pr.created_at) } prs_remaining_open = stats.raw_pull_requests(repo, :state => :open).length labels_string = closed_labels_hash.values_at(*labels).collect(&:to_i).join(",") results << "#{repo},#{opened.length},#{closed.length},#{labels_string},#{prs_remaining_open}" end File.open('prs_per_repo.csv', 'w') do |f| f.puts "Pull Requests from: #{sprint_range.first} to: #{sprint_range.last}. repo,#opened,#closed,#{labels.collect { |l| "closed_#{l}" }.join(",")},#remaining_open" results.each { |line| f.puts(line) } end
# frozen_string_literal: true require 'mongoid' module RailsAdmin module Adapters module Mongoid class Bson OBJECT_ID = if defined?(Moped::BSON) Moped::BSON::ObjectId elsif defined?(BSON::ObjectId) BSON::ObjectId end class << self def parse_object_id(value) OBJECT_ID.from_string(value) rescue StandardError => e raise e if %w[ Moped::Errors::InvalidObjectId BSON::ObjectId::Invalid BSON::InvalidObjectId ].exclude?(e.class.to_s) end end end end end end
require "rails_helper" RSpec.describe Api::V3::PatientBusinessIdentifierTransformer do describe "to_response" do let(:business_identifier) { FactoryBot.build(:patient_business_identifier) } it "removes patient_id" do transformed_business_identifier = Api::V3::PatientBusinessIdentifierTransformer.to_response(business_identifier) expect(transformed_business_identifier).not_to include("patient_id") end it "transforms metadata to JSON encoded string" do transformed_business_identifier = Api::V3::PatientBusinessIdentifierTransformer.to_response(business_identifier) transformed_metadata = transformed_business_identifier["metadata"] expect(transformed_metadata).to be_kind_of(String) expect(JSON.parse(transformed_metadata)).to be_kind_of(Hash) end end describe "from_request" do let(:business_identifier_payload) { build_business_identifier_payload } it "transforms JSON encoded metadata string into hash" do transformed_payload = Api::V3::PatientBusinessIdentifierTransformer.from_request(business_identifier_payload) transformed_metadata = transformed_payload[:metadata] expect(transformed_metadata).to be_kind_of(Hash) end end end
class UsersController < ApplicationController def show @user = User.where(id: params[:id]).first render json: @user end def update # no need to find a user (until an admin is built) @user = current_user if !@user render json: {}, status: :forbidden elsif @user.update_attributes(params[:user]) render json: @user else render json: @user, status: :failed end end end
# frozen_string_literal: true module Uploadcare module Entity # This serializer is responsible for addons handling # # @see https://uploadcare.com/api-refs/rest-api/v0.7.0/#tag/Add-Ons class Addons < Entity client_service AddonsClient attr_entity :request_id, :status, :result end end end
require 'rails_helper' RSpec.describe Team, type: :model do describe 'ActiveRecord associations' do it { is_expected.to belong_to(:tournament) } end describe 'ActiveModel validations' do it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_uniqueness_of(:name).scoped_to(:tournament_id) } end end
require 'json' require 'json/add/core' # This is a bit crazy, but we need it because the 'json/add/core' adds a really weird serialization of date fields. # It looks like this: {"json_class":"Date","y":2000,"m":1,"d":1,"sg":2299161.0} class ::Date def to_json(*_args) format('"%d-%02d-%02d"', year, month, day) end end