text
stringlengths
10
2.61M
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html mount ActionCable.server => '/cable' namespace :api do namespace :v1 do resources :users resources :characters resources :maps resources :tiles resources :campaigns resources :sessions resources :messages resources :campaigns, only: :show do get '/characters', to: 'campaigns#characters' post '/password', to: 'campaigns#password' post '/session', to: 'campaigns#session' post '/chatroom', to: 'campaigns#chatroom' end post '/users/login', to: 'users#login' resources :users, only: :show do get '/maps', to: 'users#maps' post '/characters', to: 'users#characters' end end end end
class ApplicationController < ActionController::Base before_action :configure_permitted_parameter, if: :devise_controller? def after_sign_in_path_for(resource) case resource when Customer items_path when Admin admin_path end end def after_sign_out_path_for(resource) case resource when :customer customers_sign_in_path when :admin admin_sign_in_path end end protected def configure_permitted_parameter devise_parameter_sanitizer.permit(:sign_up, keys: [:last_name, :first_name, :last_name_kana, :first_name_kana, :postal_code, :address, :telephone_number, :email]) end private def current_cart current_cart = Cart.find_by(id: session[:cart_id]) current_cart = Cart.create unless current_cart session[:cart_id] = current_cart.id current_cart end end
# frozen_string_literal: true require_relative '../modules/accessors.rb' require_relative '../modules/validation.rb' class History include Accessors attr_accessor_with_history :name def initialize @name = name end end class Strong include Accessors strong_attr_accessor :name, String def initialize @name = name end end history = History.new history.name = 'Maksim' history.name = 'Dasha' history.name = 'Sasha' p history.name_history strong = Strong.new strong.name = 'Dasha' class TestValidation include Validation validate :name, :presence validate :number, :format, /[0-9]+/i.freeze validate :type, :type, String def initialize @name = 'Maks' @number = '2141412' @type = '13' end end test = TestValidation.new test.validate!
require 'rspec' require_relative '../recent_stop_service' describe 'RecentStopService' do it 'should get recent stops from cookies' do request = stub(:cookies => {'yamba' => 'a;b'}) RecentStopService.new.get_stop_ids_from_cookie(request).should eq ['a', 'b'] end it 'should return an empty list if no cookie present' do request = stub(:cookies => {}) bus_stop = mock('bus_stop').should_not_receive(:where) RecentStopService.new.get_recent_stops(request, bus_stop).should eq [] end it 'should get the recent bus stops from db' do request = stub(:cookies => {'yamba' => 'a;b'}) bus_stop = mock('bus_stop') bus_stop.should_receive(:where).with("stop_id='a' OR stop_id='b'") RecentStopService.new.get_recent_stops(request, bus_stop) end it 'should remove the bus stop from cookie' do request = stub(:cookies => {'yamba' => 'a;b;c'}) cookie_hash = RecentStopService.new.create_cookie_without_bus_stop(request,'b') cookie_hash[:value].should eq 'a;c' end it 'should create a new cookie with the additional bus stop' do request = stub(:cookies => {'yamba' => 'a;b'}) cookie_hash = RecentStopService.new.create_cookie_with_additional_bus_stop(request,'c') cookie_hash[:value].should eq 'a;b;c' end it 'should not add the same id twice' do request = stub(:cookies => {'yamba' => 'a;b'}) cookie_hash = RecentStopService.new.create_cookie_with_additional_bus_stop(request,'b') cookie_hash[:value].should eq 'a;b' end end
# encoding: utf-8 control "V-52361" do title "The DBMS must automatically audit account disabling actions, to the extent such information is available." desc "When application accounts are disabled, user accessibility is affected. Accounts are utilized for identifying individual application users or for identifying the application processes themselves. In order to detect and respond to events affecting user accessibility and application processing, applications must audit account disabling actions and, as required, notify the appropriate individuals so they can investigate the event. Such a capability greatly reduces the risk that application accessibility will be negatively affected for extended periods of time and provides logging that can be used for forensic purposes. Note that user authentication and account management should be done via an enterprise-wide mechanism whenever possible. Examples of enterprise-level authentication/access mechanisms include, but are not limited to, Active Directory and LDAP. However, notwithstanding how accounts are managed, Oracle auditing must always be configured to capture account-disabling actions, to the extent such information is available. Note that some Oracle architectural details limit the ability to capture this information. There is a difference between actions taken by a user that generate an audit record and actions by the database itself, which do not generate an audit record. If an account is locked because of an expiration event, it is done by the database without involving the action of a user. Failed logins are logged user interactions, but the subsequent locking of the account, although initiated by user actions, is a function of the database.false" impact 0.5 tag "check": " Check Oracle settings (and also OS settings, and/or enterprise-level authentication/access mechanisms settings) to determine if account disabling actions are being audited. If account disabling actions are not being audited by Oracle, this is a finding. To see if Oracle is configured to capture audit data, enter the following SQLPlus command: SHOW PARAMETER AUDIT_TRAIL or the following SQL query: SELECT * FROM SYS.V$PARAMETER WHERE NAME = 'audit_trail'; If Oracle returns the value 'NONE', this is a finding. " tag "fix": "Configure Oracle to audit account disabling actions. Use this query to ensure auditable events are captured: ALTER SYSTEM SET AUDIT_TRAIL=<audit trail type> SCOPE=SPFILE; Audit trail type can be 'OS', 'DB', 'DB,EXTENDED', 'XML' or 'XML,EXTENDED'. After executing this statement, it may be necessary to shut down and restart the Oracle database. For more information on the configuration of auditing, please refer to 'Auditing Database Activity' in the Oracle Database 2 Day + Security Guide: http://docs.oracle.com/cd/E11882_01/server.112/e10575/tdpsg_auditing.htm and 'Verifying Security Access with Auditing' in the Oracle Database Security Guide: http://docs.oracle.com/cd/E11882_01/network.112/e36292/auditing.htm#DBSEG006 and '27 DBMS_AUDIT_MGMT' in the Oracle Database PL/SQL Packages and Types Reference: http://docs.oracle.com/cd/E11882_01/appdev.112/e40758/d_audit_mgmt.htm " # Write Check Logic Here end
require 'rails_helper' require 'support/examples/request_examples' RSpec.describe "Projects", type: :request do describe "GET /projects" do subject { get "/projects" } context "when logged in" do before do user = create(:user, :confirmed) sign_in user end it "returns http success" do subject expect(response).to have_http_status(:success) end end context "when logged out" do include_examples "failed authentication" end end describe "GET /projects/new" do subject { get "/projects/new" } context "when logged in" do before do user = create(:user, :confirmed) sign_in user end it "returns http success" do subject expect(response).to have_http_status(:success) end end context "when logged out" do include_examples "failed authentication" end end describe "POST /projects" do subject { post "/projects", params: { project: { title: "foo", name: "foo" } } } context "when logged in" do before do user = create(:user, :confirmed) sign_in user end it "redirects to /projects/:name/edit" do subject expect(response).to redirect_to("/projects/foo/edit") end end context "when logged out" do include_examples "failed authentication" end end describe "GET /projects/:name/edit" do let(:user) { create(:user, :confirmed) } let(:other_user) { create(:user, :confirmed) } let(:project) { create(:project, user: user) } subject { get "/projects/#{project.name}/edit" } context "when logged in as valid user" do before do sign_in user end context "when project is undiscarded" do it "returns http success" do subject expect(response).to have_http_status(:success) end end context "when project is discarded" do before { project.discard } include_examples "failed routing" end end context "when logged in as wrong user" do before do sign_in other_user end include_examples "failed routing" end context "when logged out" do include_examples "failed authentication" end end describe "PUT /projects/:name" do let(:user) { create(:user, :confirmed) } let(:other_user) { create(:user, :confirmed) } let(:project) { create(:project, user: user) } subject { put "/projects/#{project.name}", params: { project: { title: "foo" } } } context "when logged in as valid user" do before do sign_in user end context "when project is undiscarded" do it "redirects to /projects/:name/edit" do subject expect(response).to redirect_to("/projects/#{project.name}/edit") end end context "when project is discarded" do before { project.discard } include_examples "failed routing" end end context "when logged in as wrong user" do before do sign_in other_user end include_examples "failed routing" end context "when logged out" do include_examples "failed authentication" end end describe "DELETE /projects/:name" do let(:user) { create(:user, :confirmed) } let(:other_user) { create(:user, :confirmed) } let(:project) { create(:project, user: user) } subject { delete "/projects/#{project.name}" } context "when logged in as valid user" do before do sign_in user end context "when project is undiscarded" do it "redirects to /projects" do subject expect(response).to redirect_to("/projects") end end context "when project is discarded" do before { project.discard } include_examples "failed routing" end end context "when logged in as wrong user" do before do sign_in other_user end include_examples "failed routing" end context "when logged out" do include_examples "failed authentication" end end end
require 'rails_helper' describe User do describe "validation" do it "should pass with valid password and email" do user = FactoryGirl.build(:user) expect(user).to be_valid end it "should fail for having less than 4 characters in password" do user = FactoryGirl.build(:user, password: "12P", password_confirmation: "12P") expect(user).to_not be_valid end it "should fail for having no capital letters in password" do user = FactoryGirl.build(:user, password: "f00bar", password_confirmation: "f00bar") expect(user).to_not be_valid end it "should fail for having no numbers in password" do user = FactoryGirl.build(:user, password: "Foobar", password_confirmation: "Foobar") expect(user).to_not be_valid end it "should fail for having no @ in email" do user = FactoryGirl.build(:user, email: "foobar.fi") expect(user).to_not be_valid end end end
class SurveysController < ApplicationController include ApplicationHelper layout 'public', only: [:new_reply, :confirm] before_action :set_survey, only: [:invite, :results, :edit, :update, :destroy, :new_step, :edit_step, :edit_questions, :update_questions, :create_reply] before_action :set_recipient, only: [:new_reply, :create_reply] def index authorize_namespace Survey @surveys = current_user.survey end def confirm end def new authorize_namespace Survey @survey = Survey.new end def edit authorize_namespace @survey end def invite authorize_namespace @survey end def edit_questions authorize_namespace @survey @survey.pages = [Page.new] if @survey.pages.empty? end def new_reply @survey = @recipient.survey @page_number = params[:page_number] || 1 @page = @survey.get_page_for_recipient @recipient, @page_number.to_i recipient_data = @survey.users_data[@recipient.email] render text: translate_tags(recipient_data, render_to_string(:new_reply)), layout: false end def create_reply @survey.update reply_params page_number = params[:page_number] next_page = @survey.next_page_for_recipient @recipient, page_number.to_i unless next_page redirect_to confirm_surveys_path else redirect_to new_reply_survey_path(link_hash: params[:link_hash], page_number: next_page) end end def create authorize_namespace Survey @survey = Survey.new(survey_params) if @survey.save && current_user.add_role(:owner, @survey) redirect_to edit_questions_survey_path(@survey), notice: 'Survey was successfully created.' else render :new end end def update authorize_namespace @survey if @survey.update(survey_params) redirect_to request.referer, notice: 'Survey was successfully updated.' else render :edit end end def update_questions authorize_namespace @survey if @survey.update(survey_questions_params) redirect_to edit_questions_survey_path(@survey), notice: 'Survey was successfully updated.' else render :edit_questions end end def destroy authorize_namespace @survey @survey.destroy respond_to do |surveyat| surveyat.html { redirect_to surveys_url, notice: 'Survey was successfully destroyed.' } surveyat.json { head :no_content } end end def results respond_to do |format| format.html format.csv { send_data @survey.to_csv, filename: "results-#{@survey.name}.csv" } end end def invite authorize_namespace @survey if request.get? else emails = invite_params[:emails].split(',').map(&:strip) User.invite_all emails, @survey redirect_to surveys_path, notice: "Users invited successfully." end end private def invite_params params.require(:users).permit(:emails) end def set_survey @survey = Survey.find(params[:id]) end def set_recipient @recipient = Recipient.find_by link_hash: params[:link_hash] end def reply_params params.require(:survey).permit(recipients_attributes: [ :id, { answers_attributes: [ :id, :item_id, :value, { value: [] } ] }]) end def survey_params params.require(:survey).permit(:name, :title, :users_data_file, :email_tag, { mail_config: [ :from, :authentication, :address, :port, :domain, :user_name, :password, :enable_starttls_auto ] }) end def survey_questions_params params.require(:survey).permit(pages_attributes: [:id, :sequence, :_destroy, { conditions_attributes: [ :id, :_destroy, :reference_type, :reference, :comparator, :value ], items_attributes: [ :id, :_destroy, :sequence, :actable_type, { conditions_attributes: [ :id, :_destroy, :reference_type, :reference, :comparator, :value ], actable_attributes: [ :id, :_destroy, :title, :number, :description, :is_required, :accepts_multiple, { alternatives_attributes: [:id, :_destroy, :value]}, :content ] } ] }]) end end
class Api::V1::LessonsController < Api::V1::BaseController def show lesson = Lesson.find(params[:id]) render json: lesson end def index lessons = Lesson.all render json: lessons end end
class Account::RandomExpensesController < Account::ApplicationController def index @today = Account::DayDecorator.decorate(Users::TodayQuery.call(user: current_user)) @random_expences = Account::ExpenseDecorator.decorate_collection( Expenses::Random::TodaysQuery.call(user: current_user) ) @labels = current_user.random_expense_labels @expense = current_user.random_expenses.build end def create result = Expenses::Random::Create.call( user: current_user, params: expense_params ) if result.success? redirect_to account_random_expenses_path else @today = Account::DayDecorator.decorate(Users::TodayQuery.call(user: current_user)) @expense = result.expense @random_expences = Account::ExpenseDecorator.decorate_collection( Expenses::Random::TodaysQuery.call(user: current_user) ) @labels = current_user.random_expense_labels flash[:error] = @expense.errors.full_messages.join("\n") render :index end end def edit @expense = current_user.random_expenses.find(params[:id]) @labels = current_user.random_expense_labels end def update @expense = current_user.random_expenses.find(params[:id]) result = Expenses::Random::Update.call(expense: @expense, params: expense_params) if result.success? redirect_to account_random_expenses_path else @expense = result.expense @labels = current_user.random_expense_labels flash[:error] = @expense.errors.full_messages.join("\n") render :edit end end def destroy end private def expense_params params.require(:random_expense).permit(:id, :label_id, :amount_cents, :amount_currency) end end
# Цепочка обязанностей class ChainService class Builder def initialize @instance = ChainService.new end # Добавить обработчик цепочки # @param [Proc]block # @return [Builder] def add_handler(&block) @instance.handlers << block self end # Тип ошибки, при которой необходимо вызывать следующий по порядку обработчик цепочки # @param [Class<StandardError>]error_class def error(error_class) @instance.error_class = error_class self end # @return [ChainService] def create; @instance end end private_constant :Builder attr_reader :handlers attr_accessor :error_class # @return [Builder] def self.build; Builder.new end def initialize @handlers = [] @error_class = StandardError end # Вызов цепочки, начиная с первого обработчика # @raise [@error_class] def call! @handlers.each_with_index do |x, i| begin return x.call rescue @error_class => e raise e if i == @handlers.size - 1 end end end end class CurrenciesChainService < ChainService # Цепочка сервисов выдачи валюты формируется на основе имен классов в .env # @param [String]base # @return [CurrenciesChainService] def self.from_env(base) builder = build.error(Faraday::ConnectionFailed) ENV["CURRENCY_SERVICES_CHAIN"].split(/\s*,\s*/).each do |c| method = c.constantize.new.method(:get_currency!) builder = builder.add_handler { method.parameters.empty?? method.call: method.call(base) } end builder.create end end
module Jobs class ::DiscourseSimpleCalendar::UpdateMattermostUsernames < Jobs::Scheduled every 1.hour def execute(args) api_key = SiteSetting.discourse_simple_calendar_mattermost_api_key post_id = SiteSetting.discourse_simple_calendar_holiday_post_id server = SiteSetting.discourse_simple_calendar_mattermost_server if api_key.blank? || post_id.blank? || server.blank? return end # Fetch all mattermost users response = Excon.get("#{server}/api/v4/users", headers: { "Authorization": "Bearer #{api_key}" }) mattermost_users = JSON.parse(response.body, symbolize_names: true) # Build a list of discourse users currently on holiday users_on_holiday = [] pcf = PostCustomField.find_by(name: ::DiscourseSimpleCalendar::CALENDAR_DETAILS_CUSTOM_FIELD, post_id: post_id) details = JSON.parse(pcf.value) details.each do |post_number, detail| from_time = Time.parse(detail[::DiscourseSimpleCalendar::FROM_INDEX]) to = detail[::DiscourseSimpleCalendar::TO_INDEX] || detail[::DiscourseSimpleCalendar::FROM_INDEX] to_time = Time.parse(to) to_time += 24.hours unless detail[::DiscourseSimpleCalendar::TO_INDEX] # Add 24 hours if no explicit 'to' time if Time.zone.now > from_time && Time.zone.now < to_time users_on_holiday << detail[::DiscourseSimpleCalendar::USERNAME_INDEX] end end # puts "Users on holiday are #{users_on_holiday}" # Loop over mattermost users mattermost_users.each do |user| mattermost_username = user[:username] marked_on_holiday = !!mattermost_username.chomp!("-v") discourse_user = User.find_by_email(user[:email]) next unless discourse_user discourse_username = discourse_user.username on_holiday = users_on_holiday.include?(discourse_username) update_username = false if on_holiday && !marked_on_holiday update_username = "#{mattermost_username}-v" elsif !on_holiday && marked_on_holiday update_username = mattermost_username end if update_username # puts "Update #{mattermost_username} to #{update_username}" Excon.put("#{server}/api/v4/users/#{user[:id]}/patch", headers: { "Authorization": "Bearer #{api_key}" }, body: { username: update_username }.to_json) end end end end end
desc 'Populate players' namespace :data_seeding do task populate_players: :environment do HTTParty.get('https://fantasy.premierleague.com/drf/elements').each do |player| fpl_player = Player.find_or_create_by(id: player['id']) fpl_player.update( first_name: player['first_name'], last_name: player['second_name'], squad_number: player['squad_number'], team_code: player['team_code'], photo: player['photo'], web_name: player['web_name'], status: player['status'], code: player['code'], news: player['news'], now_cost: player['now_cost'], chance_of_playing_this_round: player['chance_of_playing_this_round'], chance_of_playing_next_round: player['chance_of_playing_next_round'], value_form: player['value_form']&.to_d, value_season: player['value_season']&.to_d, cost_change_start: player['cost_change_start'], cost_change_event: player['cost_change_event'], cost_change_start_fall: player['cost_change_start_fall'], cost_change_event_fall: player['cost_change_event_fall'], in_dreamteam: player['in_dreamteam'], dreamteam_count: player['dreamteam_count'], selected_by_percent: player['selected_by_percent']&.to_d, form: player['form']&.to_d, transfers_out: player['transfers_out'], transfers_in: player['transfers_in'], transfers_out_event: player['transfers_out_event'], transfers_in_event: player['transfers_in_event'], loans_in: player['loans_in'], loans_out: player['loans_out'], loaned_in: player['loaned_in'], loaned_out: player['loaned_out'], total_points: player['total_points'], event_points: player['event_points'], points_per_game: player['points_per_game']&.to_d, ep_this: player['ep_this']&.to_d, ep_next: player['ep_next']&.to_d, special: player['special'], minutes: player['minutes'], goals_scored: player['goals_scored'], goals_conceded: player['goals_conceded'], assists: player['assists'], clean_sheets: player['clean_sheets'], own_goals: player['own_goals'], penalties_missed: player['penalties_missed'], penalties_saved: player['penalties_saved'], yellow_cards: player['yellow_cards'], red_cards: player['red_cards'], saves: player['saves'], bonus: player['bonus'], bps: player['bps'], influence: player['influence']&.to_d, creativity: player['creativity']&.to_d, threat: player['threat']&.to_d, ict_index: player['ict_index']&.to_d, ea_index: player['ea_index'], position_id: player['element_type'], team_id: player['team'] ) end Player.all.each do |player| pfhs = HTTParty.get("https://fantasy.premierleague.com/drf/element-summary/#{player.id}")['history'] .select { |pfh| pfh['minutes'] > 0 } next unless pfhs player_stats_arr.each do |stat| player.update(stat => pfhs.inject(0) { |sum, pfh| sum + pfh[stat] }) end end end private def player_stats_arr %w(open_play_crosses big_chances_created clearances_blocks_interceptions recoveries key_passes tackles winning_goals dribbles fouls errors_leading_to_goal big_chances_missed offside attempted_passes target_missed) end end
require 'rails_helper' describe Queries::UserQueryType do types = GraphQL::Define::TypeDefiner.instance it 'defines a field user that returns Types::UserType type' do expect(subject).to have_a_field(:user).that_returns(Types::UserType) end context 'with users' do let(:users) { users = create_list(:user, 3) users.each do |user| user.posts.create(attributes_for(:post)) end users } let(:a_user) { users.last } it 'returns a user of id' do result = subject.fields['user'].resolve(nil, {id: a_user.id}, nil) expect(result.name).to eq(a_user.name) expect(result.posts.first.title).to eq(a_user.posts.first.title) end describe 'a query is given' do let(:vars) { {} } let(:ctx) { {} } let(:result) { TextblogSchema.execute(query_string, variables: vars, context: ctx) } context 'to request a single user' do let(:vars) { {"id": a_user.id} } let(:query_string) { %|query user($id: ID!) { user(id: $id) { name posts { title } } }| } it 'returns a name and uid' do result_user = result["data"]["user"] expect(result_user["name"]).to eq(a_user.name) expect(result_user["id"]).to be_nil expect(result_user["posts"].first["title"]).to eq(a_user.posts.first.title) end end end end end
#encoding: utf-8 require 'test_helper' #TODO ref test class Web::Admin::PartnersControllerTest < ActionController::TestCase setup do user = create :user sign_in user @partner_attrs = attributes_for :partner end #NEW def test_new get :new assert_response :success assert_template :new end def test_new_when_not_logged sign_out :user get :new assert_response :found end #CREATE def test_create_with_valid_params assert_difference('Partner.count', 1, 'add one record') { post :create, partner: @partner_attrs } assert_redirected_to admin_partners_path assert_equal "Партнер добавлен", flash[:notice] end def test_create_with_invalid_params invalid_attrs = @partner_attrs.merge(name_ru: '') assert_no_difference('Partner.count', 'should\'t add one record') { post :create, partner: invalid_attrs } assert_template :new end #INDEX def test_get_index @active_partners = [] create :partner, state: :deleted 2.times { @active_partners << create(:partner) } @active_partners = Partner.where(state: :active) get :index assert @active_partners.to_ary == assigns[:partners].to_ary, 'should by only active partner records assigns' assert_template :index assert_response :success end #DELETE #archive the partner def test_should_archive_partner partner = create :partner assert_difference('Partner.count',0,'archive one partner') { delete :destroy, id: partner } active = Partner.active.find_by_id(partner.id) deleted = Partner.deleted.find_by_id(partner.id) assert_nil active assert_not_nil deleted assert_response :found assert_redirected_to admin_partners_path assert_equal 'Партнер отправлен в архив', flash[:notice] end def test_should_not_destroy_partner_when_not_logged sign_out :user partner = create :partner assert_no_difference('Partner.find(partner.id).state.hash','partner not archived') do delete :destroy, id: partner end end #DELETED #list of archived partners def test_show_list_archived_partners get :deleted assert_response :success assert_template :deleted end #RESTORE #restore the archived partner def test_restore_of_archived_partner archived = create :partner, deleted_at: Time.current, state: :deleted post :restore, id: archived assert_equal 'active', archived.reload.state, 'should set active to partner' assert_nil archived.reload.deleted_at, 'should delete deleted_at time' assert_response :found assert_redirected_to admin_partners_path end #EDIT #edit a partner def test_edit @partner = create :partner get :edit, id: @partner assert_response :success assert_template :edit end #UPDATE test 'should put update partner' do @partner = create :partner put :update, id: @partner assert_redirected_to admin_partners_url, 'not redirect on partners list' end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Serialized field', type: :request do subject { page } context 'with serialized objects' do before do RailsAdmin.config do |c| c.model User do configure :roles, :serialized end end @user = FactoryBot.create :user visit edit_path(model_name: 'user', id: @user.id) fill_in 'user[roles]', with: %(['admin', 'user']) click_button 'Save' # first(:button, "Save").click @user.reload end it 'saves the serialized data' do expect(@user.roles).to eq(%w[admin user]) end end context 'with serialized objects of Mongoid', mongoid: true do before do @field_test = FactoryBot.create :field_test visit edit_path(model_name: 'field_test', id: @field_test.id) end it 'saves the serialized data' do fill_in 'field_test[array_field]', with: '[4, 2]' fill_in 'field_test[hash_field]', with: '{ a: 6, b: 2 }' click_button 'Save' # first(:button, "Save").click @field_test.reload expect(@field_test.array_field).to eq([4, 2]) expect(@field_test.hash_field).to eq('a' => 6, 'b' => 2) end it 'clears data when empty string is passed' do fill_in 'field_test[array_field]', with: '' fill_in 'field_test[hash_field]', with: '' click_button 'Save' # first(:button, "Save").click @field_test.reload expect(@field_test.array_field).to eq(nil) expect(@field_test.hash_field).to eq(nil) end end end
class ReservationMailer < ActionMailer::Base default from: "Reservester <app19024275@heroku.com>" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.reservation_mailer.reservation_notification.subject # def reservation_notification(reservation) @reservation = reservation @email = reservation.email @restaurant = Restaurant.find_by(id: @reservation[:restaurant_id]) mail( to: @email, subject: "Thanks for making a reservation through Reservester!") end end
# So this is quite a lot of crazy monkeypatching, just to create the # //= wrap_with_anonymous_function directive. Probably should have punted # in the first place :/ # # (And it depends on using UnglifierJS since I had to patch the compressor too) # Now this is also being used to munge build names into served assets on the fly though WrapMarker = "/** _anon_wrapper_ **/" AnonFunc = "(function() {" AnonWrapperStartPieces = [WrapMarker, AnonFunc] AnonWrapperStart = AnonWrapperStartPieces.join(';') AnonWrapperEnd = "})(); #{WrapMarker}" AnonWrapperStartRegex = Regexp.new("#{Regexp.escape(AnonWrapperStart)}\\s*$") AnonWrapperCleanupRegex = Regexp.new("(#{Regexp.escape(AnonWrapperStartPieces[0])}[\\s\\n]*;?[\\s\\n]*\\(function\\(\\)\\s*\\{\\s*\\n*;?\\n*)", Regexp::MULTILINE) AnonWrapperEndCleanupRegex = Regexp.new("(\\}\\)\\(\\);?\\s*#{Regexp.escape(WrapMarker)};?\\n*)", Regexp::MULTILINE) def munge_build_names_for_dependencies(project_name, data) deps = Rails.application.config.hubspot.dependencies_for[project_name] || {} served_projects = Rails.application.config.hubspot.static_project_names # Quick check to see if any munging is necessary (for performance) return if not data.include? '/static/' or not project_name deps.each do |dep, build_name| data.gsub! "#{dep}/static/", "#{dep}/#{build_name}/" unless served_projects.include? dep end end def extract_project_from_path(path) return unless path tokens = path.split('/').compact index = tokens.rindex { |token| token =~ /^static(-\d\.\d+)?$/ } Rails.application.config.hubspot.aliased_project_name(tokens[index - 1]) if index && index > 0 end # Monkey patch the directive processors to ensure that the build names are interpreted # before any preprocessing happens (so that files are imported correctly) class HubspotAssetDirectiveProcessor < Sprockets::DirectiveProcessor def prepare project_name = extract_project_from_path file munge_build_names_for_dependencies project_name, data super end end class HubspotBundleJSDirectiveProcessor < HubspotAssetDirectiveProcessor def render(scope=Object.new, locals={}, &block) result = super if result and AnonWrapperCleanupRegex =~ result result.gsub! AnonWrapperCleanupRegex, "" result = AnonWrapperStart + "\n" + result end result end end class HubspotJSDirectiveProcessor < HubspotAssetDirectiveProcessor @is_wrapped = false def process_wrap_with_anonymous_function_directive @is_wrapped = true end def render(scope=Object.new, locals={}, &block) result = super if @is_wrapped result = AnonWrapperStart + "\n" + result + "\n" + AnonWrapperEnd end result end end class HubspotBundleCSSDirectiveProcessor < HubspotAssetDirectiveProcessor end class HubspotCSSDirectiveProcessor < HubspotAssetDirectiveProcessor end # Replace the current js processor with our own: Rails.application.assets.unregister_processor('application/javascript', Sprockets::DirectiveProcessor) Rails.application.assets.register_processor('application/javascript', HubspotJSDirectiveProcessor) # Replace the current css processor with our own: Rails.application.assets.unregister_processor('text/css', Sprockets::DirectiveProcessor) Rails.application.assets.register_processor('text/css', HubspotCSSDirectiveProcessor) Rails.application.assets.register_bundle_processor('application/javascript', HubspotBundleJSDirectiveProcessor) Rails.application.assets.register_bundle_processor('text/css', HubspotBundleCSSDirectiveProcessor) class Uglifier alias_method :_orig_compile, :compile def wrapped_compile(source) wrapped = false if source and AnonWrapperCleanupRegex =~ source and AnonWrapperEndCleanupRegex =~ source wrapped = true source.gsub! AnonWrapperCleanupRegex, "" source.gsub! AnonWrapperEndCleanupRegex, "" end result = _orig_compile(source) if wrapped join_char = Rails.env.compressed? ? "" : "\n" result = [AnonWrapperStart, result, AnonWrapperEnd].join(join_char) end result end alias_method :compile, :wrapped_compile alias_method :compress, :wrapped_compile end # Monkey patch the sass compiler so that imported sass files are munged module Sass module Tree class ImportNode < RootNode alias_method :_orig_import, :import def import if @imported_filename.include? '/static/' project_name = extract_project_from_path filename munge_build_names_for_dependencies project_name, @imported_filename end _orig_import() end alias_method :import, :import end end end # Monkey patch PorcessedAsset to ensure that the build names are interpreted # after preprocessing happens module Sprockets class ProcessedAsset < Asset alias_method :_orig_initialize, :initialize def wrapped_initialize(environment, logical_path, pathname) _orig_initialize(environment, logical_path, pathname) project_name = extract_project_from_path logical_path munge_build_names_for_dependencies project_name, @source end alias_method :initialize, :wrapped_initialize end end # Setting this variable will cause the compilier to ignore all "//= require ..." lines, # essentially preventing any bundles from being compiled if ENV['INGNORE_BUNDLE_DIRECTIVES'] HubspotAssetDirectiveProcessor.class_eval do def process_require_directive(path) end def process_include_directive(path) end def process_require_directory_directive(path = ".") end def process_require_tree_directive(path = ".") end end end # Fix the location of the generated sprite and ensure that the generated sprite # filename is consistent across deps, versions, etc # Overwriting method from /compass-0.12.2/lib/compass/sass_extensions/sprites/sprite_methods.rb module Compass module SassExtensions module Sprites module SpriteMethods def filename project = extract_project_from_path name_and_hash path = Rails.application.config.hubspot.served_projects_path_map[project] || Rails.application.config.hubspot.served_dependency_path_map[project] File.join File.split(path)[0], name_and_hash end def strip_version_from_path(path) path.gsub(/\/static-\d+\.\d+\//, '/static/') end def uniqueness_hash @uniqueness_hash ||= begin sum = Digest::MD5.new sum << SPRITE_VERSION sum << layout # Strip the version from this top-level path as well sum << strip_version_from_path(path) images.each do |image| # Remove the version from the relative_file path so that the hash generated # is consistent across different builds stripped_relative_file = strip_version_from_path(image.relative_file.to_s) sum << stripped_relative_file # Skips :relative_file since that is handled above [:height, :width, :repeat, :spacing, :position, :digest].each do |attr| sum << image.send(attr).to_s end end sum.hexdigest[0...10] end @uniqueness_hash end end end end end
class AddIndexToMessages < ActiveRecord::Migration[5.1] def change add_index :messages, :token, unique: true end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :user do sequence(:first_name) { |n| "dave#{n}" } last_name "mulls" sequence(:user_name) { |n| "dmulls#{n}" } end end
require 'spec_helper' describe 'hiera_lookups::one' do context 'with actual hiera lookup' do it { is_expected.to contain_user('user1').with_password(/.+/) } end context 'with fake hiera lookup' do let(:hiera_config) { 'spec/fixtures/hiera-good.yaml' } it do is_expected.to contain_user('user1').with_password('fake_password_string') end end context 'when lookup() does not specify a default value' do context 'when hieradb is missing' do let(:hiera_config) { '/dev/null' } it { is_expected.to_not compile } it { is_expected.to raise_error(Puppet::DataBinding::LookupError) } end context 'when key is not in hiera' do let(:hiera_config) { 'spec/fixtures/hiera-bad.yaml' } it { is_expected.to_not compile } it { is_expected.to raise_error(Puppet::DataBinding::LookupError) } end end end
# typed: false require "spec_helper" describe Vndb::Constants do describe Vndb::Constants::VERSION do it "must respond with a String" do _(Vndb::Constants::VERSION).must_be_instance_of String end it "must be compatible with SemVer 2.0" do require "support/semver_regexp" _(Vndb::Constants::VERSION.match?(Vndb::Spec::Support::SEMVER_REGEXP)).must_be(:==, true) end it "must be frozen" do _(Vndb::Constants::VERSION.frozen?).must_be(:==, true) end end describe Vndb::Constants::URL do it "must be frozen" do _(Vndb::Constants::URL.frozen?).must_be(:==, true) end end describe Vndb::Constants::EOT do it "must be frozen" do _(Vndb::Constants::EOT.frozen?).must_be(:==, true) end end end
class Booking < ActiveRecord::Base validates :user_id, presence: true, uniqueness: {scope: :project_id} validates :project_id, presence: true belongs_to :user belongs_to :project end
module BSON class ObjectId def to_bson(*args) self end def self.cast_from_string(string) ObjectId.from_string(string) unless string.blank? end end end
module Warden module Rails module Helpers extend ActiveSupport::Concern included do helper_method :warden, :logged_in?, :logged_user, :current_user end def warden request.env['warden'] end def login(*args) warden.authenticate(*args) end def login?(*args) warden.authenticate?(*args) end def login!(*args) warden.authenticate!(*args) end def logout(*scopes) # Without this inspect the session does not clear. warden.raw_session.inspect warden.logout(*scopes) end def logged_in?(scope = nil) scope ||= warden.config.default_scope warden.authenticated?(scope) end def logged_user(opts = {}) warden.user(opts) end alias_method :current_user, :logged_user def set_user(user, opts = {}) warden.set_user(user, opts) end end end end
require 'pstore' class ActiveStore < PStore def initialize dbname super(dbname) end def create key, value transaction do self[key]= value end end def read key transaction do self[key] end end def update key, value transaction do abort if self[key].nil? end transaction do self[key]= value end end def delete key transaction do self.delete key end end def keys transaction do roots end end def list all = [] transaction do roots.each do |key| all << self[key] end end all end end
json.array!(@offers) do |offer| json.extract! offer, :product_id, :buyer, :seller, :buyer_price, :seller_price json.url offer_url(offer, format: :json) end
require 'rails_helper' describe Project, type: :model do let!(:project) { create(:project) } it { should have_many(:targets) } it { expect(project).to validate_presence_of :name } it { should have_and_belong_to_many(:users) } end
class PastExamsController < ApplicationController before_action :set_past_exam, only: [:show, :update, :destroy] # GET /past_exams def index page = params[:page].try(:to_i) || 1 per_page = params[:per_page].try(:to_i) || 25 filters = PastExam.includes(:course, :uploader).ransack(params[:q]) @past_exams = filters.result(distnct: true).page(page).per(per_page) render json: { current_page: page, total_pages: @past_exams.total_pages, total_count: @past_exams.total_count, data: @past_exams } end # GET /past_exams/1 def show render json: @past_exam end # POST /past_exams def create @past_exam = PastExam.new(past_exam_params) if @past_exam.save render json: @past_exam, status: :created, location: @past_exam else render json: @past_exam.errors, status: :unprocessable_entity end end # PATCH/PUT /past_exams/1 def update if @past_exam.update(past_exam_params) render json: @past_exam else render json: @past_exam.errors, status: :unprocessable_entity end end # DELETE /past_exams/1 def destroy @past_exam.destroy end private # Use callbacks to share common setup or constraints between actions. def set_past_exam @past_exam = PastExam.includes(:course, :uploader).find(params[:id]) end # Only allow a trusted parameter "white list" through. def past_exam_params params.fetch(:past_exam, {}) .permit(:description, :file, :course_id) end end
# frozen_string_literal: true class RemoveIchnotaxonFromTaxa < ActiveRecord::Migration[6.0] def change safety_assured do remove_column :taxa, :ichnotaxon, :boolean, default: false, null: false end end end
class PostSerializer < ActiveModel::Serializer attributes :id belongs_to :user belongs_to :topic end
class Product < ActiveRecord::Base has_many :contracts has_many :vendors, :through => :contracts validates :name, :description, presence: true validates :price, numericality: true has_attached_file :image, :styles => { :medium => "400x400>", :thumb=> "200x200" }, :default_url => "/images/:style/missing.png" validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ end
class ChangesController < ApplicationController before_action :set_change, only: [:show, :edit, :update, :destroy, :restore] # GET /changes def index @changes = Change.paginate(:page => params[:page]) end # GET /changes/1 def show end # GET /changes/new def new @change = Change.new end # GET /changes/1/edit def edit end def restore work_order = @change.work_order if @change.state==0 state = 1 elsif @change.state==2 || @change.state == 5 state = 3 else state = @change.state end if work_order.update({code: @change.code, title: @change.title, description: @change.description, bill_order: @change.bill_order, state: state}) change_register = Change.new() change_register.work_order = work_order change_register.user = current_user change_register.user_assigned = work_order.user_assigned change_register.code = work_order.code change_register.title = work_order.title change_register.description = work_order.description change_register.bill_order = work_order.bill_order change_register.state = state + 10 change_register.save end redirect_to work_order, notice: 'Se ha vuelto a este punto.' end # POST /changes def create @change = Change.new(change_params) if @change.save redirect_to @change, notice: 'Change was successfully created.' else render :new end end # PATCH/PUT /changes/1 def update if @change.update(change_params) redirect_to @change, notice: 'Change was successfully updated.' else render :edit end end # DELETE /changes/1 def destroy @change.destroy redirect_to changes_url, notice: 'Change was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_change @change = Change.find(params[:id]) end # Only allow a trusted parameter "white list" through. def change_params params.require(:change).permit(:work_order_id, :user_id, :state, :code, :title, :description, :bill_order_id) end end
A, B = gets.chomp.split(" ").map(&:to_i) if A.even? || B.even? puts 'No' else puts 'Yes' end
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? # fields to be filled when user is signing-up, signing-in or updating their profile through #devise protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up) {|u| u.permit(:first_name, :last_name, :username, :address, :email, :password, :remember_me)} devise_parameter_sanitizer.permit(:sign_in) {|u| u.permit(:email, :password, :remember_me)} devise_parameter_sanitizer.permit(:account_update) {|u| u.permit(:first_name, :last_name, :username, :address, :about, :email, :password, :current_password, :remember_me)} end end
require 'csv' class Admin::PasswordsController < Admin::ApplicationController before_action :set_password_tier def index @role = params[:role].presence @passwords = Password.where(password_tier: @password_tier).includes(person: :team).order('people.login ASC') @passwords = @passwords.where(people: {role: @role}) if @role respond_to do |format| format.html { render :index } format.csv do csv = CSV.generate do |c| c << %w(team_slug team_name role login name password) @passwords.each do |password| c << [password.person&.team&.slug, password.person&.team&.name, password.person.role, password.person.login, password.person.display_name, password.plaintext_password] end end render plain: csv end end end def generate @people = Person.all @people = @people.where(role: params[:role]) if params[:role].present? @people = @people.where(login: params[:login]) if params[:login].present? @password_tier.generate!(people: @people, overwrite: params[:overwrite].present?) flash[:notice] = 'Password generated' redirect_to password_tier_passwords_path(@password_tier) end def print PrintPasswordsJob.perform_later(@password_tier, role: params[:role].presence) flash[:notice] = 'Queued password printing' redirect_to password_tier_passwords_path(@password_tier) end def export_to_cms unless @password_tier.contest&.taskable? flash[:error] = "No CMS Remote Task Target present to the contest" return redirect_to(password_tier_passwords_path(@password_tier)) end ApplicationRecord.transaction do @remote_task = RemoteTask.create!( description: "Participation Export to CMS from: #{@password_tier.description}", kind: 'CmsBatchLoadParticipation', task_arguments: {'password_tier_id' => @password_tier.id}, status: :creating ) @remote_task.executions.create!(status: :created, target_kind: @password_tier.contest.cms_remote_task_driver, target: @password_tier.contest.cms_remote_task_target) @remote_task.status = :created @remote_task.save! end @remote_task.perform_later! return redirect_to(remote_task_executions_path(@remote_task), notice: 'Created remote task') end def export_to_machines @remote_task = RemoteTask.create!( description: "User Export to machines from: #{@password_tier.description}", kind: 'Adduser', task_arguments: {'password_tier_id' => @password_tier.id}, status: :creating, ) CreateRemoteTaskExecutionsJob.perform_later(@remote_task, machines: true) return redirect_to(remote_task_executions_path(@remote_task), notice: 'Created remote task') end private def set_password_tier @password_tier = PasswordTier.find(params[:password_tier_id]) end end
class StaticPagesController < ApplicationController def home @banners = Banner.published @candidates = Candidate.published end def about set_meta_tags({ title: "黨組織及主要成員", description: "社會民主黨是由一群長期關心台灣各個議題的公民所組成。和你一樣,我們對既有政治的不滿已經很久了。現在,我們決定自己捲起袖子,動手打造台灣的新政治。", keywords: "社會民主黨,社民黨,公民", og: { type: 'article', title: "黨組織及主要成員", description: "社會民主黨是由一群長期關心台灣各個議題的公民所組成。和你一樣,我們對既有政治的不滿已經很久了。現在,我們決定自己捲起袖子,動手打造台灣的新政治。" } }) end def donate_plan @candidates = Candidate.all @article = Article.find(1) set_meta_tags({ title: "捐款支持", description: "立刻捐款支持社會民主黨,幫助我們一起打造台灣的新政治!", keywords: "捐款支持,社會民主黨,社民黨,sdparty", og: { type: 'article', title: "捐款支持", description: "立刻捐款支持社會民主黨,幫助我們一起打造台灣的新政治!" } }) end def donate_one @candidates = Candidate.all @article = Article.find(1) set_meta_tags({ title: "捐款支持", description: "立刻捐款支持社會民主黨,幫助我們一起打造台灣的新政治!", keywords: "捐款支持,社會民主黨,社民黨,sdparty", og: { type: 'article', title: "捐款支持", description: "立刻捐款支持社會民主黨,幫助我們一起打造台灣的新政治!" } }) end def fundraising set_meta_tags({ title: "小額捐款", description: "小額捐款支持社會民主黨,幫助我們一起打造台灣的新政治!", keywords: "小額捐款,捐款支持,社會民主黨,社民黨,sdparty", og: { type: 'article', title: "小額捐款", description: "小額捐款支持社會民主黨,幫助我們一起打造台灣的新政治!" } }) end def join set_meta_tags({ title: "成為黨員", description: "加入社會民主黨,成為社會民主黨黨員,一起改革台灣政治!", keywords: "成為黨員,入黨申請,成為社會民主黨黨員", og: { type: 'article', title: "成為黨員", description: "加入社會民主黨,成為社會民主黨黨員,一起改革台灣政治!" } }) end def programs set_meta_tags({ title: "政綱", description: "政綱內容包含三大類:新經濟、新政治、新社會。一起來了解社會民主黨政綱。", keywords: "政綱,政綱草案,新經濟,新政治,新社會", og: { type: 'article', title: "政綱", description: "政綱內容包含三大類:新經濟、新政治、新社會。一起來了解社會民主黨政綱。" } }) respond_to do |format| format.html format.json end end def programs_1 set_meta_tags({ title: "新經濟政綱", description: "新經濟政綱 - 社民黨認為當務之急是改革稅制與產業政策,並強化財產的社會責任。", keywords: "新經濟政綱,新經濟,政綱草案", og: { type: 'article', title: "新經濟政綱", description: "新經濟政綱 - 社民黨認為當務之急是改革稅制與產業政策,並強化財產的社會責任。" } }) respond_to do |format| format.html format.json end end def programs_2 set_meta_tags({ title: "新政治政綱政綱", description: "新政治政綱 - 社民黨主張,新的政治力量必須進入國會,重新設定政治議題,改革政治體制,重塑政治文化,最終改變台灣的政治版圖。", keywords: "新政治政綱,新政治,政綱草案", og: { type: 'article', title: "新政治政綱政綱", description: "新政治政綱 - 社民黨主張,新的政治力量必須進入國會,重新設定政治議題,改革政治體制,重塑政治文化,最終改變台灣的政治版圖。" } }) respond_to do |format| format.html format.json end end def programs_3 set_meta_tags({ title: "新社會政綱", description: "新社會政綱 - 社民黨主張國家應積極保障社會不同群體尊嚴與基本權益,創造平等的多元社會,促進實質平等與社會正義的實現。", keywords: "新社會政綱,新社會,政綱草案", og: { type: 'article', title: "新社會政綱", description: "新社會政綱 - 社民黨主張國家應積極保障社會不同群體尊嚴與基本權益,創造平等的多元社會,促進實質平等與社會正義的實現。" } }) respond_to do |format| format.html format.json end end def policies set_meta_tags({ title: "2016大選的五大政見草案", description: "政治能改變這一切。社會民主國家的經驗告訴我們,只要受雇者們能團結、組織起來,對抗財團資本,對抗新自由主義體制,我們就不用再忍受目前的不平等和無奈,可以自由地合作、創造和發展。", keywords: "共同政見,政見草案,2016大選,立委選舉", og: { type: 'article', title: "2016大選的五大政見草案", description: "政治能改變這一切。社會民主國家的經驗告訴我們,只要受雇者們能團結、組織起來,對抗財團資本,對抗新自由主義體制,我們就不用再忍受目前的不平等和無奈,可以自由地合作、創造和發展。" } }) respond_to do |format| format.html format.json end end def policies_1 title = "捍衛勞動權" description = "社會民主黨第一箭:提高薪資,捍衛勞動權,強化受雇階級力量" set_meta_tags({ title: "#{title}", description: "#{description}", keywords: "#{title},共同政見,政見草案,2016大選,立委選舉", og: { type: 'article', title: "#{title}", description: "#{description}" } }) respond_to do |format| format.html format.json end end def policies_2 title = "全民年金改革" description = "社會民主黨第二箭:全民年金大改革,建構平等社會安全體系" set_meta_tags({ title: "#{title}", description: "#{description}", keywords: "#{title},共同政見,政見草案,2016大選,立委選舉", og: { type: 'article', title: "#{title}", description: "#{description}" } }) respond_to do |format| format.html format.json end end def policies_3 title = "匡正稅制" description = "社會民主黨第三箭:財團富人要加稅,增進國家財政能力,強化財產的社會責任" set_meta_tags({ title: "#{title}", description: "#{description}", keywords: "#{title},共同政見,政見草案,2016大選,立委選舉", og: { type: 'article', title: "#{title}", description: "#{description}" } }) respond_to do |format| format.html format.json end end def policies_4 title = "透明監督" description = "社會民主黨第四箭:政治要公平透明、要可受監督、要不被收買" set_meta_tags({ title: "#{title}", description: "#{description}", keywords: "#{title},共同政見,政見草案,2016大選,立委選舉", og: { type: 'article', title: "#{title}", description: "#{description}" } }) respond_to do |format| format.html format.json end end def policies_5 title = "尊重差異" description = "社會民主黨第五箭:尊重差異、反對歧視,共創多元社會" set_meta_tags({ title: "#{title}", description: "#{description}", keywords: "#{title},共同政見,政見草案,2016大選,立委選舉", og: { type: 'article', title: "#{title}", description: "#{description}" } }) respond_to do |format| format.html format.json end end def policies_6 title = "推動社會經濟" description = "社會民主黨之弓:推動「社會經濟」模式,創建兼顧社會正義、社會團結、資源共享的生產方式,管制資本,發展符合社會需求、環境永續、知識與技術創新、在地化與勞工合作的新產業。" set_meta_tags({ title: "#{title}", description: "#{description}", keywords: "#{title},共同政見,政見草案,2016大選,立委選舉", og: { type: 'article', title: "#{title}", description: "#{description}" } }) respond_to do |format| format.html format.json end end def constitution end def constructing end def sitemap @articles = Article.all @candidates = Candidate.all end end
class RenameTripcastsToTriptracks < ActiveRecord::Migration def change rename_table :tripcasts, :triptracks end end
require 'rails_helper' describe SendsMessages do let(:fake_class) do class FakeClass include SendsMessages end end it 'includes a .messages method' do expect(fake_class).to respond_to(:messages) end end
module MetaWhere module Relation extend ActiveSupport::Concern included do alias_method_chain :build_arel, :metawhere alias_method_chain :build_where, :metawhere alias_method_chain :reset, :metawhere alias_method_chain :scope_for_create, :metawhere alias_method_chain :merge, :metawhere alias_method :&, :merge_with_metawhere const_get("SINGLE_VALUE_METHODS").push(:autojoin) # I'm evil. attr_accessor :autojoin_value end def autojoin(value = true, &block) new_relation = clone new_relation.send(:apply_modules, Module.new(&block)) if block_given? new_relation.autojoin_value = value new_relation end def merge_with_metawhere(r, association_name = nil) if (r && klass != r.klass) # Merging relations with different base. default_association = reflect_on_all_associations.detect {|a| a.klass == r.klass} association_name ||= default_association ? default_association.name : r.table_name.to_sym r = r.clone r.where_values.map! {|w| w.respond_to?(:to_predicate) ? {association_name => w} : w} r.joins_values.map! {|j| [Symbol, Hash].include?(j.class) ? {association_name => j} : j} end merge_without_metawhere(r) end def reset_with_metawhere @mw_unique_joins = @mw_association_joins = @mw_non_association_joins = @mw_stashed_association_joins = @mw_custom_joins = nil reset_without_metawhere end def scope_for_create_with_metawhere @scope_for_create ||= begin @create_with_value || predicate_wheres.inject({}) do |hash, where| if where.is_a?(Arel::Predicates::Equality) hash[where.operand1.name] = where.operand2.respond_to?(:value) ? where.operand2.value : where.operand2 end hash end end end def build_where_with_metawhere(*args) return if args.blank? if args.first.is_a?(String) @klass.send(:sanitize_sql, args) else predicates = [] args.each do |arg| predicates += Array.wrap( case arg when Array @klass.send(:sanitize_sql, arg) when Hash @klass.send(:expand_hash_conditions_for_aggregates, arg) else arg end ) end predicates end end def build_custom_joins(joins = [], arel = nil) arel ||= table joins.each do |join| next if join.blank? @implicit_readonly = true case join when ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation arel = arel.join(join.relation, Arel::OuterJoin).on(*join.on) when Hash, Array, Symbol if array_of_strings?(join) join_string = join.join(' ') arel = arel.join(join_string) end else arel = arel.join(join) end end arel end def custom_join_sql(*joins) arel = table joins.each do |join| next if join.blank? @implicit_readonly = true case join when Hash, Array, Symbol if array_of_strings?(join) join_string = join.join(' ') arel = arel.join(join_string) end else arel = arel.join(join) end end arel.joins(arel) end unless defined?(:custom_join_sql) def predicate_wheres join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, custom_joins) builder = MetaWhere::Builder.new(join_dependency, @autojoin_value) remove_conflicting_equality_predicates(flatten_predicates(@where_values, builder)) end def build_arel_with_metawhere arel = table joined_associations = [] join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, custom_joins) # Build wheres now to take advantage of autojoin if needed builder = MetaWhere::Builder.new(join_dependency, @autojoin_value) predicate_wheres = remove_conflicting_equality_predicates(flatten_predicates(@where_values, builder)) order_attributes = @order_values.map {|o| o.respond_to?(:to_attribute) ? o.to_attribute(builder, join_dependency.join_base) : o }.flatten.uniq.select {|o| o.present?} order_attributes.map! {|a| Arel::SqlLiteral.new(a.is_a?(String) ? a : a.to_sql)} join_dependency.graft(*stashed_association_joins) @implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty? to_join = [] join_dependency.join_associations.each do |association| if (association_relation = association.relation).is_a?(Array) to_join << [association_relation.first, association.join_class, association.association_join.first] to_join << [association_relation.last, association.join_class, association.association_join.last] else to_join << [association_relation, association.join_class, association.association_join] end end to_join.each do |tj| unless joined_associations.detect {|ja| ja[0] == tj[0] && ja[1] == tj[1] && ja[2] == tj[2] } joined_associations << tj arel = arel.join(tj[0], tj[1]).on(*tj[2]) end end arel = arel.join(custom_joins) predicate_wheres.each do |where| next if where.blank? case where when Arel::SqlLiteral arel = arel.where(where) else sql = where.is_a?(String) ? where : where.to_sql arel = arel.where(Arel::SqlLiteral.new("(#{sql})")) end end arel = arel.having(*@having_values.uniq.select{|h| h.present?}) if @having_values.present? arel = arel.take(@limit_value) if @limit_value.present? arel = arel.skip(@offset_value) if @offset_value.present? arel = arel.group(*@group_values.uniq.select{|g| g.present?}) if @group_values.present? arel = arel.order(*order_attributes) if order_attributes.present? selects = @select_values.uniq quoted_table_name = @klass.quoted_table_name if selects.present? selects.each do |s| @implicit_readonly = false arel = arel.project(s) if s.present? end else arel = arel.project(quoted_table_name + '.*') end arel = arel.from(@from_value) if @from_value.present? case @lock_value when TrueClass arel = arel.lock when String arel = arel.lock(@lock_value) end if @lock_value.present? arel end private def remove_conflicting_equality_predicates(predicates) predicates.reverse.inject([]) { |ary, w| unless w.is_a?(Arel::Predicates::Equality) && ary.any? {|p| p.is_a?(Arel::Predicates::Equality) && p.operand1.name == w.operand1.name} ary << w end ary }.reverse end def flatten_predicates(predicates, builder) predicates.map {|p| predicate = p.respond_to?(:to_predicate) ? p.to_predicate(builder) : p if predicate.is_a?(Arel::Predicates::All) flatten_predicates(predicate.predicates, builder) else predicate end }.flatten.uniq end def unique_joins @mw_unique_joins ||= @joins_values.map {|j| j.respond_to?(:strip) ? j.strip : j}.uniq end def association_joins @mw_association_joins ||= unique_joins.select{|j| [Hash, Array, Symbol].include?(j.class) && !array_of_strings?(j) } end def stashed_association_joins @mw_stashed_association_joins ||= unique_joins.select {|j| j.is_a?(ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation)} end def non_association_joins @mw_non_association_joins ||= (unique_joins - association_joins - stashed_association_joins).reject {|j| j.blank?} end def custom_joins @mw_custom_joins ||= custom_join_sql(*non_association_joins) end end end
require("rspec") require("artist") require("cd") describe(Artist) do before() do Artist.clear() end describe("#artist") do it("returns the artist name") do new_artist = Artist.new("Sufjan Stevens") expect(new_artist.artist()).to(eq("Sufjan Stevens")) end end describe("#id") do it("returns the artist id") do new_artist = Artist.new("Sufjan Stevens") expect(new_artist.id()).to(eq(1)) end end describe("#save") do it("saves the artist to the artists array") do new_artist = Artist.new("Sufjan Stevens") new_artist.save() expect(Artist.all()).to(eq([new_artist])) end end describe(".all") do it("returns all artists") do new_artist = Artist.new("Sufjan Stevens") new_artist.save() new_artist2 = Artist.new("Run the Jewels") new_artist2.save() expect(Artist.all()).to(eq([new_artist, new_artist2])) end end describe(".clear") do it("clears the artists array") do new_artist = Artist.new("Sufjan Stevens") new_artist.save() new_artist2 = Artist.new("Run the Jewels") new_artist2.save() Artist.clear() expect(Artist.all()).to(eq([])) end end describe(".search") do it("searches all artists and returns matching artist") do new_artist = Artist.new("Sufjan Stevens") new_artist.save() new_artist2 = Artist.new("Run the Jewels") new_artist2.save() expect(Artist.search("Sufjan Stevens")).to(eq(new_artist)) end end describe(".find") do it("returns an artist by its id number") do new_artist = Artist.new("Sufjan Stevens") new_artist.save() new_artist2 = Artist.new("Run the Jewels") new_artist2.save() expect(Artist.find(new_artist.id())).to(eq(new_artist)) end end describe("#add_to_artist") do it("adds a new cd to an artist") do new_cd = CD.new({:artist => "Deerhunter", :album => "Monomania"}) new_artist = Artist.new(new_cd.artist()) new_artist.add_to_artist(new_cd) expect(new_artist.cds()).to(eq([new_cd])) end end end
require_relative 'database' class SearchEngine def initialize(database, options = {}) @database = database || Database.new() @prompt_text = options[:prompt_text] || "What property? > " @search_field = options[:search_field] || :name @current_query = "" @current_result = "" end def prompt until current_query == "q" do display_prompt get_response execute_query print_result end end private attr_reader :database, :prompt_text, :search_field, :current_query, :current_result def display_prompt print prompt_text end def get_response @current_query = gets.chomp end def execute_query @current_result = database.find_by(search_field => current_query) end def print_result puts puts current_result puts end end
# Die Class 1: Numeric # I worked on this challenge [by myself, with: ] # I spent [] hours on this challenge. # 0. Pseudocode # Input: integer between 1..6 # Output: number_of_sides, random_number (between 1 and number_of_sides) # Steps: # - define a 'Die' class # - give it an assignable @sides local variable # - give it a sides method # -input: nil # -output @sides # - give it a roll method # -input: nil # -output: a random number between 1 and no_of_sides # -steps: # -sides = @sides.to_i # -side_array << (1..#{sides}).to_a # -p side_array[0].shuffle # - ################################################################################################### # 1. Initial Solution class Die def initialize(sides) unless sides > 1 raise ArgumentError.new end @no_of_sides = sides end def sides return @no_of_sides end def roll side_array = [*1..@no_of_sides] side_array.shuffle! return side_array[0] end #def roll end #class ################################################################################################### # 3. Refactored Solution class Die def initialize(sides) @no_of_sides = sides die_argument_error end def sides return_number_of_sides end def roll return_shuffled_side end end #class ################################################################################################### def die_argument_error unless @no_of_sides > 1 && @no_of_sides >= 6 raise ArgumentError.new end end ############################################################## def return_number_of_sides return @no_of_sides end ############################################################## def side_array_generator [*1..@no_of_sides] end ############################################################## def return_shuffled_side side_array = side_array_generator side_array.shuffle! return side_array[0] end =begin #########################################REFLECTION############################################### 1. What is an ArgumentError and why would you use one? An ArgumentError is an error that is raised when there are an invalid amount or type of argument being passed to a method. We raise an error in this case because our methods COULD take 0 as an arguement and be valid, but we DON'T WANT them to. A real die can't have 0 sides, so we're trying to simulate that. 2. What new Ruby methods did you implement? What challenges and successes did you have in implementing them? I learned two new methods or commands 'raise' and '*'(splat). I looked through a lot more, but because I knew it better I ended up just using '.shuffle!' instead of using one of the RNG methods the assignment reccomended. 3. What is a Ruby class? A ruby class is a kind of object that takes arguments to define built in variables. It can also have built in methods that can be called by class.method. 4. Why would you use a Ruby class? I'd imagine that when we're working with big peices of code, we'll often be recycling segments of code or using the same methods over and over. It's simpler and more efficient to store code in classes and then call it again and again. It seems more efficient that way. 5. What is the difference between a local variable and an instance variable? Instance variables exist in a class and are defined for each instance of that class. For example for the Starbucks_order class, you could have an @size instance variable and for one instance it could == 'grande' and for another it could be 'venti'. Local variables are just called by their name, no '@' symbol before the name. Also (i had to look this up) they do not give a default value of nil when called. For example if you call #chinook #=> nil, but if you call 'chinook' #=> error. 6. Where can an instance variable be used? In a class! I think that's the only place they can be used. =end
require 'spec_helper' describe Post do let!(:post) { described_class.create! } describe '#post_type' do before { post.update_column(:post_type, value) } let(:expected_default_value) { described_class::PostTypeValues::NORMAL } subject { post.reload.post_type } context 'when value is set to a valid value' do let(:value) { described_class::PostTypeValues::SPECIAL } it {should eq value} end context 'when value is set to an invalid value' do context 'which is nil' do let(:value) { nil } it {should eq expected_default_value} end context 'which is empty string' do let(:value) { ' ' } it {should eq expected_default_value} end end end describe '#category_name' do before { post.update_column(:category_name, value) } let(:expected_default_value) { nil } subject { post.reload.category_name } context 'when value is set to a valid value' do let(:value) { described_class::CategoryNameValues::DRINK } it {should eq value} end context 'when value is set to an invalid value' do context 'which is nil' do let(:value) { nil } it {should eq expected_default_value} end context 'which is empty string' do let(:value) { ' ' } it {should eq expected_default_value} end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'cli_talky_talk/version' Gem::Specification.new do |spec| spec.name = "cli-talky-talk" spec.version = CliTalkyTalk::VERSION spec.authors = ["Sean McCleary"] spec.email = ["seanmcc@gmail.com"] spec.summary = %q{Gives you a random spoken greeting} spec.description = %q{Tired of staring at the terminal waiting for tasks to complete. Wouldn't it be cool if your computer could speak to you when the task is done?} spec.homepage = "https://github.com/mrinterweb/cli-talky-talk" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "pry", "~> 0.10" end
class Triangle # write code here attr_accessor :side1, :side2, :side3 def initialize(s,ss,sss) @side1 = s @side2 = ss @side3 = sss end def kind a = @side1 b = @side2 c = @side3 d = a + b dd = a + c ddd = b + c if ((a<=0) || (b<=0) || (c<=0) ) || ((d<=c) || (dd<=b) || (ddd<=a)) raise TriangleError elsif(d > c || dd > b || ddd > a) && (a!=b) & (a!=c) & (b!=c) :scalene elsif a==b && b==c then :equilateral else :isosceles end end class TriangleError < StandardError # triangle error code def message "This triangle is illegal" end end end
# By default, <code>chart</code> plots ticks above the categories. # # You can use the <code>:ticks</code> option to disable this behavior. # filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do data = {views: {2013 => 182, 2014 => 46, 2015 => 802000000000000000000}} chart data, ticks: false end
require 'rubygems' require 'httparty' module NYTimes class Congress include HTTParty base_uri 'http://api.nytimes.com/svc/politics/v2/us/legislative/congress' def initialize(key) @format = "json" #xml is also valid self.class.default_params "api-key" => key end def roll_call_votes(congress, chamber, session, rollcall) self.class.get("/#{congress}/#{chamber}/sessions/#{session}/votes/#{rollcall}.#{@format}") end def nomination_votes(congress) self.class.get("/#{congress}/nominations.#{@format}") end def members(congress, chamber, state=nil, district=nil) #district requires a state, and is only valid if chamber is the house #TODO currently, state & district are currently ignored self.class.get("/#{congress}/#{chamber}/members.#{@format}") end def member_positions(member_id) self.class.get("/members/#{member_id}/votes.#{@format}") end def member_bio_and_roles(member_id) self.class.get("/members/#{member_id}.#{@format}") end end end
module Adminpanel class Page < ActiveRecord::Base include Adminpanel::Base def self.mount_uploader(attribute, uploader) super attribute, uploader define_method "#{attribute}_will_change!" do fields_will_change! instance_variable_set("@#{attribute}_changed", true) end define_method "#{attribute}_changed?" do instance_variable_get("@#{attribute}_changed") end define_method "write_uploader" do |column, identifier| fields[column.to_s] = identifier end define_method "read_uploader" do |column| fields[column.to_s] end end def self.whitelisted_attributes(params) params.require(self.name.to_s.underscore.split('/').last).permit! end def write_uploader(column, identifier) end def read_uploader(column) end end end
# # This file should contain all the record creation needed to seed the database with its default values. # # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # # # Examples: # # # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # # Character.create(name: 'Luke', movie: movies.first) # (1..10).each do |i| # u = User.create(email: "user#{i}@example.com", password: '123456') # u.save # u.profile.create(first_name: 'salman', last_name: "haseeb_#{i}") # (1..5).each do |j| # s = u.services.create(title: 'I will do cleaning', category: 'cleaning', description: 'this is description') # s.save # s.packages.create(name: "Basic", description: "aaaa", delivery_time: 2, revisions: 2, price: 5 ) # end # end AdminUser.create!(email: 'admin@resn.com', password: '12345resn', password_confirmation: '12345resn')
# -*- ruby encoding: utf-8 -*- if ENV['MARKETO_USER_ID'] require "minitest_helper" begin verbose, $VERBOSE = $VERBOSE, nil require 'debugger' rescue LoadError ensure $VERBOSE = verbose end $run_id = Time.now.strftime('%Y%j-%H%M%S') module Integration class TestMarketoAPILeads < Minitest::Test include MarketoIntegrationHelper # Integration tests depend on a particular order. def self.test_order :alpha end attr_reader :subject, :email def setup super @subject = @client.leads @email = "bit#{$run_id}+integration@clearfit.org" @fault = { :fault => { :faultcode => 'SOAP-ENV:Client', :faultstring => '20103 - Lead not found', :detail => { :service_exception => { :name => "mktServiceException", :message => "No lead found with EMAIL = #{@email} (20103)", :code => "20103", :"@xmlns:ns1" => "http://www.marketo.com/mktows/" } } } } end def test_01_lead_is_missing assert_nil subject.get_by_email(@email) assert subject.error? assert_equal @fault, subject.error.to_hash end def test_02_create_lead lead = subject.new(email: @email) do |l| l[:FirstName] = 'George' l[:LastName] = 'of the Jungle' end refute_nil lead.sync! refute_nil lead.id end def test_03_load_lead lead = subject.get_by_email(@email) refute_nil lead refute_nil lead.id assert_equal 'George', lead[:FirstName] assert_equal @email, lead[:Email] end def test_04_change_lead_name george = subject.get_by_email(@email) george[:FirstName] = 'Ursula' george[:LastName] = 'Stanhope' ursula = george.sync refute_equal george.object_id, ursula.object_id assert_equal george.id, ursula.id assert_equal george[:FirstName], ursula[:FirstName] assert_equal george[:LastName], 'Stanhope' assert_equal subject.get_by_email(@email)[:LastName], 'Stanhope' end def test_05_change_lead_email lead = subject.get_by_email(@email) email = @email.gsub(/\.org/, '.com') lead[:Email] = email lead2 = lead.sync refute_equal lead.object_id, lead2.object_id assert_equal lead.id, lead2.id assert_equal lead[:FirstName], lead2[:FirstName] assert_equal lead[:LastName], 'Stanhope' assert_equal lead2[:Email], email assert_equal subject.get_by_email(email)[:LastName], 'Stanhope' test_01_lead_is_missing lead[:Email] = @email refute_nil lead.sync! end end end else puts 'No MARKETO_USER_ID' end
class AddIndexForInstructorAndTime < ActiveRecord::Migration[5.1] def change add_index :courses, %w(instructor_id start_time), unique: true end end
# expect(echo("hello")).to eq("hello") # end # expect(shout("hello")).to eq("HELLO") # end # expect(repeat("hello")).to eq("hello hello") # # expect(start_of_word("hello", 1)).to eq(" # expect(first_word("Hello World")).to eq("Hello") # expect(titleize("jaws")).to eq("Jaws") # end def echo(str) str end def shout(str) str.upcase end def repeat(str, i = 2) (str * i).chars.each_slice(str.length).to_a.map(&:join).join(' ') end def start_of_word(str, int) str.chars.take(int).join end def first_word(str) str.split(' ')[0] end def titleize(str) lame_words = %w[and the or over] str.split.map.with_index do |word, idx| if idx.zero? && lame_words.include?(word) word.capitalize elsif lame_words.include?(word) word else word.capitalize end end.join(' ') end
# encoding: utf-8 module TmuxStatus module Segments class Battery < Segment def output case when battery.discharging? "#{@options[:discharging_symbol]} #{battery.percentage}%" when battery.charging? return if battery.percentage > 80 "#{@options[:charging_symbol]} #{battery.percentage}%" end end def battery @battery ||= Wrappers::AcpiBattery.new end private def default_options { bg: 0, fg: 82, bold: true, discharging_symbol: '⚡', charging_symbol: '↥' } end end end end
require_relative 'rolodex.rb' class CRM attr_accessor :title def self.run(name) crm = new(name) crm.main_menu end def initialize(name) @title = name @rolodex = Rolodex.new # TEST DATA -- REMOVE AFTER TESTING @rolodex.add_contact("irwin", "chan", "asdfasdfasd", "asdfasdfasdf") @rolodex.add_contact("sherry", "Donalds", "ghdfgdfgdg", "lsdfjlkkla") @rolodex.add_contact("Bret", "Hart", "jskdfa;", "mfoasdlfaj;sdf") @rolodex.add_contact("Gary", "Perry", "fooo@bar", "pwnpwnow") @rolodex.add_contact("Bruce", "Wayne", "jskaf;klsd;f", "cxvxcvxcvxvc") @rolodex.add_contact("Spider", "Man", "sdfsdfsdfsdfs", "notes notes notes") end # This is what attr_accessor does: # def title # @title # end # def title=(new_title) # @title = new_title # end def print_main_menu puts "1. Add a contact" puts "2. Modify a contact" puts "3. Display all contacts" puts "4. Display contact" puts "5. Display contact attribute" puts "6. Delete a contact" puts "7. Exit" end def main_menu while true print_main_menu print "Choose an option: " user_input = gets.chomp.to_i break if user_input == 7 choose_option(user_input) end end def choose_option(input) # input = user_input case input when 1 then add_contact when 2 then display_modify_menu when 3 then display_all_contacts when 4 then display_contact when 5 then display_contact_attribute when 6 then delete_contact when 7 then exit else puts "I'm sorry Dave, I'm afraid you can't do that." end end def add_contact clear_term print "First name: " first_name = gets.chomp print "Last name: " last_name = gets.chomp print "Email: " email = gets.chomp print "Notes: " notes = gets.chomp @rolodex.add_contact(first_name, last_name, email, notes) clear_term puts "Contact Added: #{first_name}, #{last_name}, #{email}, #{notes}" puts "" end def display_all_contacts clear_term @rolodex.all.each do |contact| puts "#{contact.id}: #{contact.full_name} / #{contact.email}" end end def display_modify_menu clear_term puts "Please enter the ID for the contact you wish to modify" id = gets.chomp.to_i puts "" @rolodex.display_contact_by_id(id) puts "Is this the contact you wish to modify? (yes/no)" while gets.chomp == "yes" puts "" puts "Please select the field you would like to modify:" puts "1. First name" puts "2. Last name" puts "3. Email" puts "4. Notes" puts "5. Done" selection = gets.chomp.to_i if selection == 1 print "Enter new value for First name:" first_name = gets.chomp @rolodex.modify_first_name_by_id(id, first_name) clear_term break elsif selection == 2 print "Enter new value for Last name:" last_name = gets.chomp @rolodex.modify_last_name_by_id(id, last_name) clear_term break elsif selection == 3 print "Enter new value for Email:" email = gets.chomp @rolodex.modify_email_by_id(id, email) clear_term break elsif selection == 4 print "Enter new value for Notes:" notes = gets.chomp @rolodex.modify_notes_by_id(id, notes) clear_term break elsif selection == 5 clear_term break else puts "Please enter a valid number" end end clear_term end def display_contact clear_term print "Please enter the ID of the contact you wish to display: " id = gets.chomp.to_i puts "" @rolodex.display_contact_by_id(id) puts "" end def display_contact_attribute puts "Enter the attribute you wish to display" puts "1. First name" puts "2. Last name" puts "3. Email" puts "4. Notes" print "Enter selection: " selection = gets.chomp.to_i while !(1..4).include?(selection) puts "Please enter a valid number" selection = gets.chomp.to_i end clear_term case selection when 1 then @rolodex.display_attribute_first_name when 2 then @rolodex.display_attribute_last_name when 3 then @rolodex.display_attribute_email when 4 then @rolodex.display_attribute_notes end puts "" end def delete_contact print "Enter the ID of the contact you wish to delete: " id = gets.chomp.to_i @rolodex.delete_contact_by_id(id) puts "Contact Deleted" puts "" end def clear_term puts "\e[H\e[2J" end end CRM.run("Bitmaker Labs CRM") # my_crm = CRM.new("Bitmaker Labs CRM") # my_crm.main_menu # my_crm.title # => "Bitmaker Labs CRM" # my_crm.title = "Something else"
class Post < ActiveRecord::Base belongs_to :user def self.chronological order('created_at desc') end end
module Circuit module Rack # Finds the Circuit::Site for the request. Returns a 404 if the site is not found. class MultiSite def initialize(app) @app = app end def call(env) request = ::Rack::Request.new(env) request.site = Circuit.site_store.get(request.host) unless request.site # TODO custom 404 page for site not found return [404, {}, ["Not Found"]] end @app.call(request.env) end end end end
# frozen_string_literal: true module Quilt module Performance class Connection attr_accessor :downlink attr_accessor :effective_type attr_accessor :rtt attr_accessor :type def self.from_params(params) params.transform_keys! { |key| key.underscore.to_sym } Connection.new( downlink: params[:downlink], effective_type: params[:effective_type], rtt: params[:rtt], type: params[:type] ) end def initialize(downlink:, effective_type:, rtt:, type:) @downlink = downlink @effective_type = effective_type @rtt = rtt @type = type end end end end
class Youtube include Capybara::DSL attr_reader :canal def initialize @canal = find(:xpath, "//div[@id='text-container'] //yt-formatted-string[@id='text'][@class='style-scope ytd-channel-name']") end def getTextCanal @canal.text end end
class DeploysController < ApplicationController skip_before_filter :verify_authenticity_token def create @project = Project.find_by_slug(params[:project_id]) unless @project render text: "A project with the slug '#{params[:project_id]}' could not be found", status: 404 return end @environment = params.fetch(:environment, "").titleize unless Houston.config.environments.member?(@environment) render text: "Houston is not configured to recognize an environment with the name '#{@environment}'", status: 404 return end sha = params[:commit] || params[:head_long] || params[:head] branch = params[:branch] deployer = params[:deployer] || params[:user] milliseconds = params[:duration] Deploy.create!({ project: @project, environment_name: @environment, sha: sha, branch: branch, deployer: deployer, duration: milliseconds }) head 200 end end
require 'spec_helper' describe RakutenWebService do describe '.configure' do context 'given block has one arity' do before do RakutenWebService.configure do |c| c.affiliate_id = 'dummy_affiliate_id' c.application_id = 'dummy_application_id' end end subject { RakutenWebService.configuration } describe '#affiliate_id' do subject { super().affiliate_id } it { is_expected.to eq('dummy_affiliate_id') } end describe '#application_id' do subject { super().application_id } it { is_expected.to eq('dummy_application_id') } end end context 'given block has more or less one arity' do specify 'raise ArgumentError' do expect do RakutenWebService.configure do end end.to raise_error(ArgumentError) expect do RakutenWebService.configure do |c, _| c.affiliate_id = 'dummy_affiliate_id' c.application_id = 'dummy_application_id' end end.to raise_error(ArgumentError) end end context 'call without block' do specify 'raise ArgumentError' do expect { RakutenWebService.configure }.to raise_error(ArgumentError) end end end end
class AddNewIndexesToArticle < ActiveRecord::Migration def change remove_index :articles, [:approved, :approved_at] add_index :articles, :fresh add_index :articles, [:fresh, :approved] end end
class Database attr_reader 'search_person', 'found', 'add_person' def initialize @accounts = [] @found = found end def add_person print 'What is their name? ' name = gets.chomp print 'What is their phone number? ' phone_number = gets.chomp.to_i print 'What is their address? ' address = gets.chomp print 'What is their position at the Iron Yard? ' position = gets.chomp print 'What is their salary? ' salary = gets.chomp.to_i print 'What is their Slack username? ' slack_account = gets.chomp print 'What is their GitHub username? ' github_account = gets.chomp account = Person.new(name, phone_number, address, position, salary, slack_account, github_account) @accounts << account end def search_person found = false puts 'Please input the name of the person you want to search' search_person = gets.chomp @accounts.each do |account| next unless account.name == search_person found = true puts "This is #{account.name}'s information. \nName: #{account.name} \nPhone: #{account.phone_number} \nAddress: #{account.address} \nPosition: #{account}.position} \nSalary: #{account.salary} \nSlack Account: #{account.slack_account} \nGitHub Account: #{account.github_account}" end puts "#{search_person} is not in our system.\n" if found == false end def delete_person found = false index = 0 puts "Who are you looking to terminate? " name = gets.chomp @accounts.each do |account| if account.name == name found = true puts "Account has been exterminated!" @accounts.slice!(index) end index += 1 end if found == false puts "No such account exist" end end end class Person # Saving the correct data into class attr_reader 'name', 'phone_number', 'address', 'position', 'salary', 'slack_account', 'github_account' # Defining name, phone_number, address, position, salary,slack_account, github_account def initialize(name, phone_number, address, position, salary, slack_account, github_account) @name = name @phone_number = phone_number @address = address @position = position @salary = salary @slack_account = slack_account @github_account = github_account end end data = Database.new loop do puts 'Would you like to Add (A), Search (S) or Delete (D) a person from the Iron Yard Database?' selected = gets.chomp.upcase if selected == 'A' data.add_person elsif selected == 'S' data.search_person elsif selected == 'D' data.delete_person end end
class AddEstStandoutToResults < ActiveRecord::Migration def change add_column :results, :est_standout, :float add_index :results, :est_standout end end
class HexaCpusController < ApplicationController before_action :set_hexa_cpu, only: [:show, :edit, :update, :destroy] # GET /hexa_cpus/new def new @hexa_cpu = HexaCpu.new end def exercises @exercises = HexaExercise.where(user_id: current_user.id) end # POST /hexa_cpus # POST /hexa_cpus.json def create @hexa_cpu = HexaCpu.new(hexa_cpu_params) @exercise = HexaExercise.new @exercise.name = params[:name] respond_to do |format| if @hexa_cpu.save @exercise.hexa_cpu_id = @hexa_cpu.id @exercise.user_id = current_user.id @exercise.save @hexa_ram = HexaRam.new @hexa_ram.hexa_cpu_id = @hexa_cpu.id format.html { redirect_to :controller => 'hexa_rams', :action => 'new', :id => @exercise.id } format.json { render :show, status: :created, location: @hexa_ram } else format.html { render :new } format.json { render json: @hexa_cpu.errors, status: :unprocessable_entity } end end end private # Use callbacks to share common setup or constraints between actions. def set_hexa_cpu @hexa_cpu = HexaCpu.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def hexa_cpu_params params.require(:hexa_cpu).permit(:co, :dir, :pc, :directions, :load, :store, :add, :sub) end end
class AddUserIdToItems < ActiveRecord::Migration[5.2] def change add_column :items, :seller_id, :integer, null:false, foreign_key: true add_column :items, :buyer_id, :integer, foreign_key: true end end
module LatencyStats class HistogramSettings def initialize(bins = 100, max = 30, base = 1.15) @bins = bins @max = max @base = base @max_index = @bins - 1 end def length @bins end def value(index) (@base ** (index - @bins)) * 1000 * @max end def index(ms_value) return 0 if ms_value <= 0 index = (Math.log((ms_value / 1000.0) / @max, @base) + @bins).floor [index, @max_index].min end end end
# frozen_string_literal: true module Dynflow class DelayedPlan < Serializable include Algebrick::TypeCheck attr_reader :execution_plan_uuid, :start_before attr_accessor :frozen, :start_at def initialize(world, execution_plan_uuid, start_at, start_before, args_serializer, frozen) @world = Type! world, World @execution_plan_uuid = Type! execution_plan_uuid, String @start_at = Type! start_at, Time, NilClass @start_before = Type! start_before, Time, NilClass @args_serializer = Type! args_serializer, Serializers::Abstract @frozen = Type! frozen, Algebrick::Types::Boolean end def execution_plan @execution_plan ||= @world.persistence.load_execution_plan(@execution_plan_uuid) end def plan execution_plan.root_plan_step.load_action execution_plan.generate_action_id execution_plan.generate_step_id execution_plan.plan(*@args_serializer.perform_deserialization!) end def timeout error("Execution plan could not be started before set time (#{@start_before})", 'timeout') end def error(message, history_entry = nil) execution_plan.root_plan_step.state = :error execution_plan.root_plan_step.error = ::Dynflow::ExecutionPlan::Steps::Error.new(message) execution_plan.root_plan_step.save execution_plan.update_state :stopped, history_notice: history_entry end def cancel execution_plan.root_plan_step.state = :cancelled execution_plan.root_plan_step.save execution_plan.update_state :stopped, history_notice: "Delayed task cancelled" @world.persistence.delete_delayed_plans(:execution_plan_uuid => @execution_plan_uuid) return true end def execute(future = Concurrent::Promises.resolvable_future) @world.execute(@execution_plan_uuid, future) ::Dynflow::World::Triggered[@execution_plan_uuid, future] end def to_hash recursive_to_hash :execution_plan_uuid => @execution_plan_uuid, :start_at => @start_at, :start_before => @start_before, :serialized_args => @args_serializer.serialized_args, :args_serializer => @args_serializer.class.name, :frozen => @frozen end # Retrieves arguments from the serializer # # @return [Array] array of the original arguments def args @args_serializer.perform_deserialization! if @args_serializer.args.nil? @args_serializer.args end # @api private def self.new_from_hash(world, hash, *args) serializer = Utils.constantize(hash[:args_serializer]).new(nil, hash[:serialized_args]) self.new(world, hash[:execution_plan_uuid], string_to_time(hash[:start_at]), string_to_time(hash[:start_before]), serializer, hash[:frozen] || false) rescue NameError => e error(e.message) end end end
require "rails_helper" describe PostsController do let(:user) { create(:user) } before do sign_in user end describe "POST /posts" do context "when posting a status update" do it "can post the status if all data is valid" do expect { post "/posts", params: { post: { postable_type: "Status", status_text: "Howdy!", } } }.to change { user.posts.reload.count }.from(0).to(1) expect(response).to redirect_to(timelines_path) follow_redirect! expect(response.body).to include "Howdy!" end end end end
#rules:a program that randomly generates a number representing age #the number should be between 20 and 200 #output a sentence "Teddy is xx years old!" #input: nothing needed #output: a string puts "Whose age would you like to know?" name = gets.chomp age = rand(20...200) name.empty? ? (puts "Teddy is #{age} years old today!") : (puts "#{name} is #{age} years old today!")
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) 25.times do game_data = { name: "#{Faker::RockBand.unique.name} Game", avatar: Faker::Avatar.unique.image } Game.create!(game_data) end puts "#{Game.count} games created" 25.times do tournament_data = { name: "#{Faker::University.unique.name} Tournament", game: Game.order("RANDOM()").first } Tournament.create!(tournament_data) end puts "#{Tournament.count} tournaments created" PASSWORD = 'asdf' 50.times do user_data = { username: Faker::Internet.unique.user_name, email: Faker::Internet.unique.email, password: PASSWORD, avatar: Faker::Avatar.unique.image, } User.create!(user_data) end puts "#{User.count} users created" 50.times do Tournament.order("RANDOM()").first.users << User.order("RANDOM()").first end # User.create(username:"Samuel Tully", email:"Samuel@gmail.com", password:"admin") # User.create(username:"John Wayne", email:"johnwayne@gmail.com", password:"12345") # User.create(username:"PK Banks", email:"pkbanks@gmail.com", password:"1241245245") # User.create(username:"Lewis Hamilton", email:"lewishamilton@gmail.com", password:"supernecryption") # User.create(username:"Sebastian Vettel", email:"sebastianvettel@gmail.com", password:"massiveanal") # User.create(username:"Valtteri Bottas", email:"valtteri@gmail.com", password:"thebigD") # User.create(username:"Daniel Ricciardo", email:"danielricciardo@gmail.com", password:"thesmallD") # User.create(username:"Henry Arbolaez", email:"henryarbolaez@gmail.com", password:"thedoubleDD") # # # g1 = Game.new(name:"WoW") # Tournament.create(name:"DoubleDees", game_id:g1.id) # Tournament.create(name:"LargeChestnuts", game_id:g1.id) # Tournament.create(name:"WildGuns", game_id:g1.id) # Tournament.create(name:"SwingingMelons", game_id:g1.id) # # t1 = Tournament.find_by(name:"DoubleDees") # # t2 = Tournament.find_by(name:"LargeChestnuts") # # t3 = Tournament.find_by(name:"WildGuns") # # t4 = Tournament.find_by(name:"SwingingMelons") # # t1.users << User.find_by(username:"Samuel Tully") # t1.users << User.find_by(username:"Henry Arbolaez") # t1.users << User.find_by(username:"Daniel Ricciardo") # t1.users << User.find_by(username:"Valtteri Bottas") # # t2.users << User.find_by(username:"Samuel Tully") # t2.users << User.find_by(username:"John Wayne") # t2.users << User.find_by(username:"PK Banks") # t2.users << User.find_by(username:"Lewis Hamilton") # # t3.users << User.find_by(username:"Samuel Tully") # t3.users << User.find_by(username:"Sebastian Vettel") # t3.users << User.find_by(username:"PK Banks") # t3.users << User.find_by(username:"Lewis Hamilton") # # t4.users << User.find_by(username:"Samuel Tully") # t4.users << User.find_by(username:"John Wayne") # t4.users << User.find_by(username:"Sebastian Vettel") # t4.users << User.find_by(username:"PK Banks")
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure(2) do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://atlas.hashicorp.com/search. config.vm.box = "centos/7" config.vm.box_check_update = true # Un-comment the next line to port-forward port 21 on the VM to your host # config.vm.network "forwarded_port", guest: 21, host: 2121 # Create a public network, which generally matched to bridged network. # Bridged networks make the machine appear as another physical device on # your network. config.vm.network "public_network" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. # config.vm.synced_folder "../data", "/vagrant_data" # Provider-specific configuration so you can fine-tune various # backing providers for Vagrant. These expose provider-specific options. # Example for VirtualBox: # # config.vm.provider "virtualbox" do |vb| # # Display the VirtualBox GUI when booting the machine # vb.gui = true # # # Customize the amount of memory on the VM: # vb.memory = "1024" # end # # View the documentation for the provider you are using for more # information on available options. # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies # such as FTP and Heroku are also available. See the documentation at # https://docs.vagrantup.com/v2/push/atlas.html for more information. # config.push.define "atlas" do |push| # push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME" # end # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about their specific syntax and use. # # Provision script prepared by following this guide: # http://www.krizna.com/centos/setup-ftp-server-centos-7-vsftp/ config.vm.provision "shell", inline: <<-SHELL FTPDCONF="/etc/vsftpd/vsftpd.conf" FTPUSER="ftpuser" FTPPASSWORD="testpassword" echo "Install required packages..." sudo yum -y install vim vsftpd echo "Configure FTP server..." sudo sed -i 's/anonymous_enable=YES/anonymous_enable=NO/g' ${FTPDCONF} sudo sed -i 's/#chroot_local_user=YES/chroot_local_user=YES/g' ${FTPDCONF} echo "allow_writeable_chroot=YES" | sudo tee -a ${FTPDCONF} > /dev/null echo "pasv_enable=Yes" | sudo tee -a ${FTPDCONF} > /dev/null echo "pasv_min_port=40000" | sudo tee -a ${FTPDCONF} > /dev/null echo "pasv_max_port=40100" | sudo tee -a ${FTPDCONF} > /dev/null echo "Restart FTP server and enable it on boot" sudo systemctl restart vsftpd.service sudo systemctl enable vsftpd.service echo "Configure firewall" sudo firewall-cmd --permanent --add-service=ftp sudo firewall-cmd --reload echo "Configure SELinux" sudo setsebool -P ftp_home_dir on echo "Create FTP test user" sudo useradd -m "$FTPUSER" -s /sbin/nologin echo "$FTPPASSWORD" | sudo passwd "$FTPUSER" --stdin echo "Add handy 'showips' command to show all the IPs which this VM has" echo '#!/bin/bash' | sudo tee /usr/bin/showips > /dev/null echo "ip addr show | grep 'inet ' | tr '/' ' ' | cut -f6 -d ' '" | sudo tee -a /usr/bin/showips > /dev/null sudo chmod +x /usr/bin/showips echo "Finished!" echo echo echo -e "SSH credentials are\n Username: vagrant\n Password: vagrant" | sudo tee -a /etc/issue echo echo "You can also access with: 'vagrant ssh' from your host," | sudo tee -a /etc/issue echo "but you have to be in the same directory where the Vagrantfile is" | sudo tee -a /etc/issue echo echo "You can login with your FTP client with the following credentials:" | sudo tee -a /etc/motd echo -e " Username: ${FTPUSER}\n Password: ${FTPPASSWORD}\n Port: 21 (passive mode)\n" | sudo tee -a /etc/motd echo -e "Use 'showips' command to get all the IPs which this VM has\n" | sudo tee -a /etc/motd > /dev/null echo -e "Your files will be uploaded into /home/${FTPUSER}" | sudo tee -a /etc/motd > /dev/null echo -e "Execute 'sudo su' and then 'cd /home/ftpuser/' to go there\n" | sudo tee -a /etc/motd > /dev/null echo "On one of the following IP addresses:" showips echo "And your files will be uploaded into /home/${FTPUSER}" # clear history rm -rf .bash_history history -c SHELL end
require 'colorize' require_relative 'cursor' # require_relative 'board' class Display def initialize(board) @cursor = Cursor.new([0,0],board) end def render board = @cursor.board shades = [:light_yellow, :yellow] 8.times do |i| row = (-1*i+8).to_s + ": " 8.times do |j| color = (@cursor.cursor_pos == [i,j] ? :blue : board[[i,j]].color ) row += board[[i,j]].to_str.colorize(color: color, background: shades[(i+j)%2]) row += ' ' unless j == 7 end puts row end puts " : " + ('a'..'h').to_a.join(' ') end def update_cell_color render 5.times do |i| @cursor.get_input system 'clear' render end end end
require_relative 'spec_helper' require 'Rspec' require_relative '../lib/merchant' describe Merchant do before :each do @m = Merchant.new({ :id => '5', :name => 'Turing School', :created_at => '2016-01-11', :updated_at => '2007-06-04' }) end it 'is a Merchant' do expect(@m).to be_a Merchant end it '#id' do expect(@m.id).to eq 5 end it '#name' do expect(@m.name).to eq 'Turing School' end end
class Calculator::PostageRate < Calculator preference :bottom_weight, :decimal, :default => 0 preference :top_weight, :decimal, :default => 0 preference :postage_cost, :decimal, :default => 0 def self.description "Postage rate" #I18n.t("postage_rate") end def self.unit "Weight Unit" #I18n.t('weight_unit') end def self.register super Coupon.register_calculator(self) ShippingMethod.register_calculator(self) end # as object we always get line items, as calculable we have Coupon, ShippingMethod or ShippingRate fixed def compute(order) return self.preferred_postage_cost end def available?(order_or_line_items) line_items = order_or_line_items.is_a?(Order) ? order_or_line_items.line_items : order_or_line_items total_weight = line_items.map{|li| (li.variant.weight || self.preferred_default_weight) * li.quantity }.sum if total_weight > self.preferred_bottom_weight && total_weight <= self.preferred_top_weight then return true else return false end end end
# frozen_string_literal: true module EventsHelper def results_template_selector(resource) public_organization = Organization.new(name: 'Public Templates', results_templates: ResultsTemplate.standard) private_organization = resource.organization.results_templates.present? ? resource.organization : nil organizations = [public_organization, private_organization].compact resource_type = resource.class.name.underscore.to_sym grouped_collection_select(resource_type, :results_template_id, organizations, :results_templates, :name, :id, :name, {prompt: false}, {class: "form-control dropdown-select-field", data: {target: 'results-template.dropdown', action: 'results-template#replaceCategories'}}) end def link_to_beacon_button(view_object) if view_object.beacon_url link_to event_beacon_button_text(view_object.beacon_url), url_with_protocol(view_object.beacon_url), class: 'btn btn-outline-secondary', target: '_blank' end end def link_to_download_spread_csv(view_object, current_user) if current_user&.authorized_to_edit?(view_object.event) && view_object.event_finished? link_to 'Export spreadsheet', spread_event_path(view_object.event, format: :csv, display_style: view_object.display_style, sort: view_object.sort_hash), method: :get, class: 'btn btn-md btn-success' end end def link_to_toggle_live_entry(view_object) if view_object.available_live? button_text = 'Disable live' confirm_text = "NOTE: This will suspend all live entry actions for #{view_object.event_group_names}, " + 'including any that may be in process, and will disable live follower notifications ' + 'by email and SMS text when new times are added. Are you sure you want to proceed?' else button_text = 'Enable live' confirm_text = "NOTE: This will enable live entry actions for #{view_object.event_group_names}, " + 'and will also trigger live follower notifications by email and SMS text when new times are added. ' + 'Are you sure you want to proceed?' end link_to button_text, event_group_path(view_object.event_group, event_group: {available_live: !view_object.available_live?}), data: {confirm: confirm_text}, method: :put, class: 'btn btn-md btn-warning' end def link_to_toggle_public_private(view_object) if view_object.concealed? button_text = 'Make public' confirm_text = "NOTE: This will make #{view_object.event_group_names} visible to the public, " + 'including all related efforts and people. Are you sure you want to proceed?' else button_text = 'Make private' confirm_text = "NOTE: This will conceal #{view_object.event_group_names} from the public, " + 'including all related efforts. Are you sure you want to proceed?' end link_to button_text, event_group_path(view_object.event_group, event_group: {concealed: !view_object.concealed?}), data: {confirm: confirm_text}, method: :put, class: 'btn btn-md btn-warning' end def suggested_match_id_hash(efforts) efforts.select(&:suggested_match).map { |effort| [effort.id, effort.suggested_match.id] }.to_h end def suggested_match_count(efforts) suggested_match_id_hash(efforts).size end def data_status(status_int) Effort.data_statuses.key(status_int) end def event_staging_app_page(view_object) (view_object.respond_to?(:display_style)) && (view_object.display_style == 'splits') ? 'splits' : 'entrants' end end
require 'rails_helper' RSpec.describe Flag, type: :model do context 'schema' do it { is_expected.to have_db_column(:user_id).of_type(:integer) } it { is_expected.to have_db_column(:flaggable_id).of_type(:integer) } it { is_expected.to have_db_column(:flaggable_type).of_type(:string) } it { is_expected.to have_db_column(:created_at).of_type(:datetime) } it { is_expected.to have_db_column(:updated_at).of_type(:datetime) } it { is_expected.to have_db_index(:user_id) } it { is_expected.to have_db_index([:flaggable_type, :flaggable_id]) } end context 'validations' do it { is_expected.to validate_presence_of(:user_id) } it { is_expected.to validate_presence_of(:flaggable_id) } it { is_expected.to validate_presence_of(:flaggable_type) } end context 'assocations' do it { is_expected.to belong_to(:flaggable) } it { is_expected.to belong_to(:user) } end end
class PaymentsController < ApplicationController def index @person = Person.find(params[:person_id]) @payments = @person.payments end def create @person = Person.find(params[:person_id]) @payment = Payment.new(payment_params) if @payment.save redirect_to person_path(@person) else render 'new' end end def new @person = Person.find(params[:person_id]) @payment = Payment.new end private def payment_params params.require(:payment).permit(:description, :amount, :timelog) end end
#--- # Excerpted from "Rails 4 Test Prescriptions", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/nrtest2 for more book information. #--- require "rails_helper" describe CreatesProject do it "creates a project given a name" do creator = CreatesProject.new(name: "Project Runway") creator.build expect(creator.project.name).to eq("Project Runway") end end
#!/usr/bin/env gem build # encoding: utf-8 # Run ./form.gemspec or gem build form.gemspec # NOTE: we can't use require_relative because when we run gem build, it use eval for executing this file require File.expand_path("../lib/formidable/version", __FILE__) require "base64" Gem::Specification.new do |s| s.name = "formidable" s.version = Formidable::VERSION s.authors = ["Jakub Stastny aka Botanicus", "Pavel Kunc"] s.homepage = "http://github.com/botanicus/formidable" s.summary = "" # TODO: summary s.description = "" # TODO: long description s.cert_chain = nil Base64.decode64("c3Rhc3RueUAxMDFpZGVhcy5jeg==\n") s.has_rdoc = true # files s.files = `git ls-files`.split("\n") s.require_paths = ["lib"] # Ruby version s.required_ruby_version = ::Gem::Requirement.new(">= 1.9") begin require "changelog" rescue LoadError warn "You have to have changelog gem installed for post install message" else s.post_install_message = CHANGELOG.new.version_changes end # RubyForge s.rubyforge_project = "formidable" end
class Api::V1::GroupsController < Api::ApiController before_action :assert_user before_action :assert_group, only: [:update, :destroy, :add_membership] # POST /api/groups/list.json def list @groups = paginate(Api::Group.base.base_users.with_users) render json: @groups.as_json(Api::Group::Json::LIST) end # POST /api/groups/show.json def show @group = Api::Group.base.base_users.base_group_users.with_users.with_group_users(@user.id).filter_by_id(params[:id]).first render json: @group.as_json(Api::Group::Json::SHOW) end # POST /api/groups/create.json def create @group = Api::Group.new(group_params) @group.owner_id = @user.id if @group.save render json: @group.as_json(Api::Group::Json::SHOW) else render_errors(:unprocessable_entity, @group.errors) end end # POST /api/groups/update.json def update if @group.nil? render_error(:expectation_failed, 'No se encontro el grupo') elsif @group.owner_id != @user.id render_error(:unauthorized, 'Tu cuenta ha sido baneada, contacta a un administrador.') @user.active = false @user.save else if @group.update(group_params) render json: @group.as_json(Api::Group::Json::SHOW) else render_errors(:unprocessable_entity, @group.errors); end end end # POST /api/groups/destroy.json def destroy if @group.destroy render json: @group.as_json(Api::Group::Json::SHOW) else render_error(:expectation_failed, "Group couldn't be deleted.") end end # POST /api/groups/add_membership.json def add_membership @group_user = GroupUser.new @group_user.user_id = @user.id @group_user.group_id = params[:id] if @group_user.save render json: @group_user else render_errors(:unprocessable_entity, @group_user.errors); end end # POST /api/groups/destroy_membership.json def destroy_membership @group_user = GroupUser.base.filter_by_user(@user.id).first if @group_user.destroy render json: @group_user else render_errors(:expectation_failed, "No se pudo dejar el grupo.") end end # POST /api/groups/accept_membership.json def accept_membership @group_user = GroupUser.base.filter_by_user(params[:id]).first @group_user.status = GroupUser::Status::MEMBER if @group_user.save render json: @group_user else render_errors(:unprocessable_entity, @group_user.errors); end end protected def assert_group @group = Group.filter_by_id(params[:id]).first end def group_params params.permit(:name) end end
ENV["RAILS_ENV"] ||= "test" require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require 'capybara/rails' require 'minitest/pride' Capybara.default_driver = :rack_test class ActionDispatch::IntegrationTest include Capybara::DSL self.use_transactional_fixtures=false DatabaseCleaner.strategy = :truncation end class ActiveSupport::TestCase ActiveRecord::Migration.check_pending! self.use_transactional_fixtures=true # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. # # Note: You'll currently still have to declare fixtures explicitly in integration tests # -- they do not yet inherit this setting fixtures :all # Add more helper methods to be used by all tests here... def create_user_for_login_tests @email='admin@admin.com' @password='thisisatest' role=FactoryGirl.create :role role.users.create name: 'Test', email: @email, password: @password, password_confirmation: @password end def set_string(size) test_string='a' (size-1).times {test_string+='a'} test_string end def check_system_section(name, indicator, smiley) is_image_in_section? "##{name}", smiley, 1 is_text_in_section? "##{name}", indicator is_text_in_section? "##{name}", name is_text_in_section? "##{name}", "Incident Details" end def json(body) JSON.parse(body, symbolize_names: true) end end
FactoryGirl.define do factory :ear, :class => Refinery::Ears::Ear do sequence(:headline) { |n| "refinery#{n}" } end end
# Модель статистики не связанных с перерегистрацией данных class Cohort < ActiveRecord::Base KINDS = [ :organizations_by_kind, :projects_by_organization_kind, :projects_by_msu_subdivisions, :users_by_organization_kind, :users_by_msu_subdivisions, :directions_of_science, :directions_of_science_by_msu_subdivisions, :research_areas, :research_areas_by_msu_subdivisions, :critical_technologies, :critical_technologies_by_msu_subdivisions ] KINDS.each do |kind| scope kind, where(kind: kind).order("date desc, id desc") end before_create :set_date serialize :data def self.dump transaction do KINDS.each do |kind| new { |c| c.kind = kind }.dump end end end def self.human_kind_name(kind) I18n.t("cohorts.#{kind}") end def dump self.data = send("#{kind}_data") save! end def self.to_chart chart = [] if head = scoped.first ids = head.data.map { |c| c[0] } chart << ["Дата"].push(*head.data.map { |c| c[1] }) scoped.map do |c| chart << [c.pub_date].push(*c.to_row(ids)) end end chart.each do |row| row.collect! { |x| x.nil? ? 0 : x } end end def self.to_charts charts = {} max_row_size = scoped.map{|x| x.data.first[2].map(&:first).size}.max scoped.each do |cohort| ids = cohort.data.first[2].map(&:first) cohort.data.each do |group| charts[group[1]] ||= [["Дата"].push(*group[2].map { |d| d[1] })] datas = Array.new max_row_size, 0 ids.map do |id| if val = group[2].find { |c| c[0] == id } val[2] end end.each_with_index { |x, i| datas[i] = x } charts[group[1]] << [cohort.pub_date].push(*datas) end end charts end def pub_date I18n.l date, format: :long end def to_row(ids) ids.map do |id| if val = data.find { |c| c[0] == id } val[2] end end end private def organizations_by_kind_data OrganizationKind.all.map do |kind| [kind.id, kind.name, kind.organizations.with_state(:active).count] end end def projects_by_organization_kind_data OrganizationKind.all.map do |kind| count = Project.with_state(:active).joins(:organization). where(organizations: { state: "active", organization_kind_id: kind.id }). count [kind.id, kind.name, count] end end def projects_by_msu_subdivisions_data Organization.msu.subdivisions.order("name").map do |sub| count = Project.with_state(:active).joins(user: :memberships). where(memberships: { state: :active, subdivision_id: sub.id }).count [sub.id, sub.name, count] end end def users_by_organization_kind_data OrganizationKind.all.map do |kind| count = User.joins(memberships: :organization).with_state(:sured). where(organizations: { organization_kind_id: kind.id}). where(memberships: { state: "active" }).count [kind.id, kind.name, count] end end def users_by_msu_subdivisions_data Organization.msu.subdivisions.order("name").map do |sub| count = User.joins(:memberships).with_state(:sured). where(memberships: { state: "active", subdivision_id: sub.id }).count [sub.id, sub.name, count] end end def directions_of_science_data DirectionOfScience.all.map do |dir| count = Project.joins("join direction_of_sciences_projects on direction_of_sciences_projects.project_id = projects.id and direction_of_sciences_projects.direction_of_science_id = #{dir.id}"). count [dir.id, dir.name, count] end end def directions_of_science_by_msu_subdivisions_data DirectionOfScience.all.map do |dir| map = Organization.msu.subdivisions.order("name").map do |sub| count = Project.joins("join direction_of_sciences_projects on direction_of_sciences_projects.project_id = projects.id and direction_of_sciences_projects.direction_of_science_id = #{dir.id}"). joins(user: :memberships).where(memberships: { subdivision_id: sub.id }). count [sub.id, sub.name, count] end [dir.id, dir.name, map] end end def research_areas_data ResearchArea.all.map do |area| count = Project.joins("join projects_research_areas on projects_research_areas.project_id = projects.id and projects_research_areas.research_area_id = #{area.id}"). count [area.id, area.name, count] end end def research_areas_by_msu_subdivisions_data ResearchArea.all.map do |area| map = Organization.msu.subdivisions.order("name").map do |sub| count = Project.joins("join projects_research_areas on projects_research_areas.project_id = projects.id and projects_research_areas.research_area_id = #{area.id}"). joins(user: :memberships).where(memberships: { subdivision_id: sub.id }). count [sub.id, sub.name, count] end [area.id, area.name, map] end end def critical_technologies_data CriticalTechnology.all.map do |tech| count = Project.joins("join critical_technologies_projects on critical_technologies_projects.project_id = projects.id and critical_technologies_projects.critical_technology_id = #{tech.id}"). count [tech.id, tech.name, count] end end def critical_technologies_by_msu_subdivisions_data CriticalTechnology.all.map do |tech| map = Organization.msu.subdivisions.order("name").map do |sub| count = Project.joins("join critical_technologies_projects on critical_technologies_projects.project_id = projects.id and critical_technologies_projects.critical_technology_id = #{tech.id}"). joins(user: :memberships).where(memberships: { subdivision_id: sub.id }). count [sub.id, sub.name, count] end [tech.id, tech.name, map] end end def set_date self.date = Date.current end end
require 'test_helper' class HairusersControllerTest < ActionController::TestCase setup do @hairuser = hairusers(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:hairusers) end test "should get new" do get :new assert_response :success end test "should create hairuser" do assert_difference('Hairuser.count') do post :create, hairuser: { } end assert_redirected_to hairuser_path(assigns(:hairuser)) end test "should show hairuser" do get :show, id: @hairuser assert_response :success end test "should get edit" do get :edit, id: @hairuser assert_response :success end test "should update hairuser" do patch :update, id: @hairuser, hairuser: { } assert_redirected_to hairuser_path(assigns(:hairuser)) end test "should destroy hairuser" do assert_difference('Hairuser.count', -1) do delete :destroy, id: @hairuser end assert_redirected_to hairusers_path end end
class Api::PartnersController < ApiController before_filter :authenticate_user_from_token! def show @partner = Partner.find show_params[:partner_id] unless @partner.users.pluck(:id).push(@partner.primary_user_id).include? current_user.id raise UnauthorizedAccessError end end private def show_params params.require :partner_id params.permit :partner_id end end
module EZAPIClient class BaseRequest include Virtus.model attribute :username, String attribute :password, String attribute :eks_path, String attribute :prv_path, String attribute :host, String attribute :path, String, lazy: true, default: :default_path attribute :endpoint, String, lazy: true, default: :default_endpoint attribute :logger, Object attribute :log, Boolean def call HTTParty.post(endpoint, { headers: { 'Content-Type' => "application/json" }, body: body.to_json, }) end private def default_endpoint full_path = if path.nil? nil elsif path[0].eql?("/") path else "/#{path}" end uri = URI.parse(host) uri.path = full_path uri.to_s end def default_path fail "Override me" end end end
require 'spec_helper' shared_examples 'encoded file state machine' do |model| let(:zencoder_options) do Pageflow.config.zencoder_options end describe '#publish event', :inline_resque => true do before do stub_request(:get, /#{zencoder_options[:s3_host_alias]}/) .to_return(:status => 200, :body => File.read('spec/fixtures/image.jpg')) end it 'creates zencoder job for file' do file = create(model, :on_filesystem) allow(Pageflow::ZencoderApi).to receive(:instance).and_return(ZencoderApiDouble.finished) file.publish expect(Pageflow::ZencoderApi.instance).to have_received(:create_job).with(file.reload.output_definition) end it 'polls zencoder' do file = create(model, :on_filesystem) allow(Pageflow::ZencoderApi).to receive(:instance).and_return(ZencoderApiDouble.once_pending_then_finished) file.publish expect(Pageflow::ZencoderApi.instance).to have_received(:get_info).with(file.reload.job_id).twice end it 'sets state to encoded after job has finished' do file = create(model, :on_filesystem) allow(Pageflow::ZencoderApi).to receive(:instance).and_return(ZencoderApiDouble.finished) file.publish expect(file.reload.state).to eq('encoded') end end describe '#retry event', :inline_resque => true do before do stub_request(:get, /#{zencoder_options[:s3_host_alias]}/) .to_return(:status => 200, :body => File.read('spec/fixtures/image.jpg')) end context 'when upload to s3 failed' do it 'sets state to encoded after job has finished' do file = create(model, :upload_to_s3_failed) allow(Pageflow::ZencoderApi).to receive(:instance).and_return(ZencoderApiDouble.finished) file.retry expect(file.reload.state).to eq('encoded') end end context 'when encoding failed' do it 'creates zencoder job for file' do file = create(model, :encoding_failed) allow(Pageflow::ZencoderApi).to receive(:instance).and_return(ZencoderApiDouble.finished) file.retry! expect(Pageflow::ZencoderApi.instance).to have_received(:create_job).with(file.reload.output_definition) end it 'polls zencoder' do file = create(model, :encoding_failed) allow(Pageflow::ZencoderApi).to receive(:instance).and_return(ZencoderApiDouble.once_pending_then_finished) file.retry! expect(Pageflow::ZencoderApi.instance).to have_received(:get_info).with(file.reload.job_id).twice end it 'sets state to encoded after job has finished' do file = create(model, :encoding_failed) allow(Pageflow::ZencoderApi).to receive(:instance).and_return(ZencoderApiDouble.finished) file.retry expect(file.reload.state).to eq('encoded') end end end end
module GpdbInstances class MembersController < ApplicationController wrap_parameters :account, :include => [:db_username, :db_password, :owner_id] def index accounts = GpdbInstance.find(params[:gpdb_instance_id]).accounts present paginate(accounts.includes(:owner).order(:id)) end def create gpdb_instance = GpdbInstance.unshared.owned_by(current_user).find(params[:gpdb_instance_id]) account = gpdb_instance.accounts.find_or_initialize_by_owner_id(params[:account][:owner_id]) account.attributes = params[:account] Gpdb::ConnectionChecker.check!(gpdb_instance, account) account.save! present account, :status => :created end def update gpdb_instance = GpdbInstance.owned_by(current_user).find(params[:gpdb_instance_id]) account = gpdb_instance.accounts.find(params[:id]) account.attributes = params[:account] Gpdb::ConnectionChecker.check!(gpdb_instance, account) account.save! present account, :status => :ok end def destroy gpdb_instance = GpdbInstance.owned_by(current_user).find(params[:gpdb_instance_id]) account = gpdb_instance.accounts.find(params[:id]) account.destroy render :json => {} end end end
class AddTypeIndexToUsers < ActiveRecord::Migration def change add_index :users, :type end end
require 'rails_helper' describe Order do it "has a valid factory" do expect(build(:order)).to be_valid end it "is valid with a name, address, email, and payment_type" do expect(build(:order)).to be_valid end it "is invalid without a name" do order = build(:order, name: nil) order.valid? expect(order.errors[:name]).to include("can't be blank") end it "is invalid without an address" do order = build(:order, address: "") order.valid? expect(order.errors[:address]).to include("can't be blank") end it "is invalid without an email" do order = build(:order, email: nil) order.valid? expect(order.errors[:email]).to include("can't be blank") end it "is invalid with email not in valid email format" do order = build(:order, email: "email") order.valid? expect(order.errors[:email]).to include("is invalid") end it "is invalid without a payment_type" do order = build(:order, payment_type: nil) order.valid? expect(order.errors[:payment_type]).to include("can't be blank") end it "is invalid with wrong payment_type" do expect{ build(:order, payment_type: "Grab Pay") }.to raise_error(ArgumentError) end describe "adding line_items from cart" do before :each do @cart = create(:cart) @restaurant = create(:restaurant, address:"kolla sabang, jakarta") @food = create(:food, restaurant: @restaurant) @line_item = create(:line_item, food:@food, cart: @cart) @order = build(:order) end it "add line_items to order" do @order.add_line_items(@cart) @order.save expect(@order.line_items.size).to eq(1) end it "removes line_items from cart" do expect{ @order.add_line_items(@cart) @order.save }.to change(@cart.line_items, :count).by(-1) end end describe "adding discount to order" do context "with valid voucher" do before :each do @voucher = create(:voucher, code: 'VOUCHER1', amount: 15.0, unit_type: "% (Persentage)", max_amount: 10000) @cart = create(:cart) @restaurant = create(:restaurant, address: "kolla sabang, jakarta") @food = create(:food, price: 100000.0, restaurant: @restaurant) @line_item = create(:line_item, quantity: 1, food: @food, cart: @cart) @order = create(:order, voucher: @voucher, address: "sarinah, jakarta") @order.add_line_items(@cart) end it "can calculate sub total price" do @order.save expect(@order.sub_total).to eq(100000) end it "can calculate sub total + delivery_cost" do @order.save expect(@order.sub_total_delivery).to eq(100488) end context "with voucher in percent" do it "can calculate discount" do voucher = create(:voucher, code: 'VOUCHER2', amount: 5, unit_type: "% (Persentage)", max_amount: 10000) order = create(:order, voucher: voucher) order.add_line_items(@cart) order.save expect(order.discount).to eq(5024) end it "changes discount to max_amount if discount is bigger than max_amount" do @order.save expect(@order.discount).to eq(10000) end end context "with voucher in rupiah" do it "can calculate discount" do voucher = create(:voucher, amount: 5000, unit_type: "Rp (Rupiah)", max_amount: 10000) order = create(:order, voucher: voucher) order.add_line_items(@cart) order.save expect(order.discount).to eq(5000) end end it "can calculate total price" do @order.save expect(@order.total_price).to eq(90488) end end it "is invalid with a wrong voucher" do order = build(:order, voucher_code: "okokok") order.valid? expect(order.errors[:voucher_code]).to include("is not exist") end context "with invalid voucher" do it "is invalid with a wrong voucher" do order = build(:order, voucher_code: "okokok") order.valid? expect(order.errors[:voucher_code]).to include("is not exist") end it "is invalid with an expire voucher" do order = build(:order, voucher_code: "10PERSEN") voucher = create(:voucher, code: "10PERSEN", valid_from:"2015-10-10", valid_through:"2015-10-11") order.valid? expect(order.errors[:voucher_code]).to include("is expire") end end end it "save user to order's user_id" do user = create(:user) order = create(:order, user: user) expect(order.user_id).to eq(user.id) end it "is invalid if gopay credit less than total price of order" do user = create(:user) order = build(:order, payment_type: "Go Pay", total: 300000, user: user) order.valid? expect(order.errors[:payment_type]).to include("Gopay credit is not enough") end # it "is reduce the gopay credit" do # user = create(:user) # order = create(:order, payment_type: "Go Pay", total: 50000, user: user) # order.reduce_gopay # expect(user.gopay).to eq(150000) # end describe "adding google maps apis service" do before :each do @cart = create(:cart) @restaurant = create(:restaurant, address: "kolla sabang, jakarta") @food = create(:food, restaurant: @restaurant) @line_item = create(:line_item, food:@food, cart:@cart) @order = build(:order, address: "sarinah, jakarta") @order.add_line_items(@cart) end it "get json data from google api" do expect(@order.get_google_api).not_to eq(nil) end it "calculate distance from origin and destination" do expect(@order.distance).to eq(325) end it "calculate delivary cost from distance" do expect(@order.delivery_cost).to eq(488) end end end
# frozen_string_literal: true require 'etcd' require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'puppet_x', 'etcd', 'etcd_config.rb')) Puppet::Type.newtype(:etcd_key) do @doc = %q{Creates a key in a remote etcd database. Connection options for etcd are specified in the etcd.conf file located in your puppet confdir (Use puppet config print --confdir on your master to find this.) Example: etcd_key { '/test/key': ensure => present, value => 'Test value!', } } def pre_run_check # Check we can parse config and connect to etcd config = PuppetX::Etcd::EtcdConfig.new Puppet.debug("Loaded etcd config: #{config.config_hash}") client = Etcd.client(config.config_hash) begin client.leader rescue StandardError => e raise Puppet::Error, "Failed pre-run etcd connection validation: #{e.message}." end end newproperty(:ensure) do desc "Whether the key should exist in etcd or not. You can use ensure => directory to ensure an empty diectory." newvalue(:present) { provider.create } newvalue(:directory) { provider.create } newvalue(:absent) { provider.destroy } defaultto :present end newparam(:path) do desc "The path of the key in the etcd structure." validate do |value| raise ArgumentError "Invalid etcd path #{value}" unless value.match(%r{(\/\w+)+}) end isnamevar end newproperty(:value) do desc "The value of the key. Mutually exclusive with directory => true." end end
require 'optparse' module Hourglass class Runner import org.eclipse.swt.events.ShellListener import org.eclipse.swt.browser.OpenWindowListener import org.eclipse.swt.browser.CloseWindowListener import org.eclipse.swt.browser.VisibilityWindowListener import org.eclipse.swt.browser.TitleListener import org.eclipse.swt.browser.TitleEvent import org.eclipse.swt.browser.ProgressListener class ShellWrapper < Delegator include ShellListener attr_reader :shell, :frame_x, :frame_y, :name alias :__getobj__ :shell @@sizes = {} def initialize(*args) options = args.last.is_a?(Hash) ? args.pop : {} @name = options['name'] @shell = Swt::Widgets::Shell.new(*args) width, height = @@sizes[name] || options['default_size'] || [600, 400] @shell.set_size(width, height) if options['center'] pt = options['center'] @shell.set_location(pt.x - (width / 2), pt.y - (height / 2)) end @shell.layout = Swt::Layout::FillLayout.new @shell.add_shell_listener(self) super(@shell) end # To satisfy ShellListener def shellIconified(event); end def shellDeiconified(event); end def shellDeactivated(event); end def shellClosed(event) # remember the shell size point = @shell.get_size @@sizes[@name] = [point.x, point.y] end def shellActivated(event) client_area = @shell.client_area @frame_x = @shell.size.x - client_area.width @frame_y = @shell.size.y - client_area.height end def set_client_area_size(width, height) @shell.set_size(width + @frame_x, height + @frame_y) end end class BrowserWrapper < Delegator include OpenWindowListener include CloseWindowListener include VisibilityWindowListener include TitleListener include ProgressListener attr_reader :browser alias :__getobj__ :browser def initialize(shell_wrapper) @shell_wrapper = shell_wrapper @browser = Swt::Browser.new(shell_wrapper.shell, Swt::SWT::NONE) @browser.add_open_window_listener(self) @browser.add_close_window_listener(self) @browser.add_visibility_window_listener(self) @browser.add_title_listener(self) @browser.add_progress_listener(self) super(@browser) end def open(event) # For OpenWindowListener # pop-up support if event.required display = @shell_wrapper.get_display location = display.get_cursor_location popup_shell = ShellWrapper.new(display, Swt::SWT::APPLICATION_MODAL | Swt::SWT::TITLE | Swt::SWT::CLOSE | Swt::SWT::RESIZE, 'name' => 'popup', 'center' => location, 'default_size' => [675, 200]) popup_browser = BrowserWrapper.new(popup_shell) event.browser = popup_browser.browser else puts "Not required!" end end def close(event) # For CloseWindowListener @shell_wrapper.close end def hide(event) # For VisibilityWindowListener @shell_wrapper.visible = false end def show(event) # For VisibilityWindowListener @shell_wrapper.location = event.location if event.location @shell_wrapper.open end def changed(event) # For TitleListener and ProgressListener case event when TitleEvent @shell_wrapper.set_text(event.title) end end def completed(event) # For ProgressListener @shell_wrapper.set_client_area_size(outer_body_width, outer_body_height); end def outer_body_width browser.evaluate("return $('body').outerWidth(true);") end def outer_body_height browser.evaluate("return $('body').outerHeight(true);") end end def initialize(argv = ARGV) options = {} OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.on("-s", "--server-only", "Only run the web server") do |s| options['server_only'] = s end end.parse(argv) Database.migrate! if start_server if options['server_only'] @web_thread.join else start_browser end end Activity.stop_current_activities end def start_server handler = Rack::Handler.get('mongrel') settings = Application.settings @web_server = Mongrel::HttpServer.new(settings.bind, settings.port, 950, 0, 60) @web_server.register('/', handler.new(Application)) success = false begin @web_thread = @web_server.run success = true rescue Errno::EADDRINUSE => e puts "Can't start web server, port already in use. Aborting..." end success end def start_browser display = Swt::Widgets::Display.new shell_wrapper = ShellWrapper.new(display, 'name' => 'main') browser_wrapper = BrowserWrapper.new(shell_wrapper) browser_wrapper.set_url("http://localhost:4567", nil, ["user-agent: SWT"].to_java(:String)) shell_wrapper.open while !shell_wrapper.disposed? if !display.read_and_dispatch display.sleep end end display.dispose end end end
class AuctionSearch include ActiveModel::Model attr_accessor :brand_ids, :clothing_condition_id, :child_configuration_id, :child_genders, :clothing_size_ids, :clothing_type_ids, :season_ids, :search_term, :siblings_type, :sort_by def initialize(params = {}) return unless params.is_a? Hash params.each do |name, value| send("#{name}=", value) end end def compact(value) if value.is_a? String value.blank? ? nil : value.gsub(/\[|\]/,'').split(/,/).map(&:to_i) else value = value.delete_if(&:blank?) value.empty? ? nil : value.map(&:to_i) end end def brand_ids=(value) @brand_ids = compact(value) end def clothing_condition_id=(value) @clothing_condition_id = compact(value) end def clothing_size_ids=(value) @clothing_size_ids = compact(value) end def clothing_type_ids=(value) @clothing_type_ids = compact(value) end def season_ids=(value) @season_ids = compact(value) end def child_configuration if child_configuration_id.present? @child_configuration = ChildConfiguration.find(child_configuration_id) elsif @siblings_type and @child_genders @child_configuration = ChildConfiguration.where(siblings_type: params[:siblings_type], genders: params[:genders]).first end @child_configuration end def needs_child_genders? !(child_configuration_id || child_genders) end def possible_child_configurations if child_configuration [child_configuration] elsif siblings_type ChildConfiguration.where(:siblings_type => siblings_type) else ChildConfiguration.all end end def siblings_type @siblings_type || child_configuration.try(:siblings_type) end def needs_siblings_type? !(child_configuration_id || siblings_type) end def auctions composed_scope = Auction.active composed_scope = composed_scope.joins(:child_configurations).where('auction_child_configurations.child_configuration_id' => possible_child_configurations) if brand_ids.present? composed_scope = composed_scope.where(brand_id: brand_ids) end if clothing_condition_id.present? composed_scope = composed_scope.where(clothing_condition_id: clothing_condition_id) end if clothing_size_ids.present? composed_scope = composed_scope.joins(:clothing_sizes).where('auction_clothing_sizes.clothing_size_id' => clothing_size_ids) end if clothing_type_ids.present? composed_scope = composed_scope.where(clothing_type_id: clothing_type_ids) end if season_ids.present? composed_scope = composed_scope.where(season_id: season_ids) end if search_term.present? q = "%#{search_term.gsub(' ', '%').downcase}%" composed_scope = composed_scope.joins(:brand).joins(:user).where("LOWER(brands.name) LIKE :q OR LOWER(title) LIKE :q OR LOWER(description) LIKE :q OR LOWER(users.first_name) LIKE :q OR LOWER(users.last_name) LIKE :q", :q => q) end case sort_by when "Price" # composed_scope = composed_scope.sort{|a,b| a.buy_now_price <=> b.buy_now_price} when "Title" composed_scope = composed_scope.order("title ASC") else composed_scope = composed_scope.order("ends_at ASC") end composed_scope.uniq end def to_hash(merge_in = {}) hash = {} hash[:siblings_type] = siblings_type if siblings_type hash[:search_term] = search_term if search_term hash.merge!(merge_in) { auction_search: hash } end end
class ProfessorsController < ApplicationController before_action :set_professor, only: [:show, :edit, :update, :destroy] def index @professors = Professor.all end def show @rating = @professor.ratings.new end def new @professor = Professor.new @professor.ratings.new end def edit end def create @professor = Professor.new(professor_params) @professor.ratings.each do |new_rating| new_rating.user_id = current_user.id end if @professor.save redirect_to @professor, notice: 'Professor was successfully created.' else render :new end end def update if @professor.update(professor_params) redirect_to @professor, notice: 'Professor was successfully updated.' else render :edit end end def destroy @professor.destroy redirect_to professors_url end private def set_professor @professor = Professor.find(params[:id]) end def professor_params params.require(:professor).permit(:first, :last, :university, ratings_attributes: [:course, :comment, :rating]) end end
require 'test_helper' class BaseTest < Test::Unit::TestCase def setup CampusBooks.api_key = 'SmT8KuLkGvy7SexotRTB' end should "parse OK response and return just the response" do expected_response = { "status"=>"ok", "version"=>"1", "page" => { "name"=>"bookinfo", "rating"=>"5.0", "category"=>nil, "title"=>"The Ruby Programming Language", "isbn10"=>"0596516177", "tried_amazon"=>"1", "author"=>"David Flanagan - Yukihiro Matsumoto", "msrp"=>"39.99", "rank"=>"19257", "isbn13"=>"9780596516178", "publisher"=>"O'Reilly Media, Inc.", "pages"=>"446", "edition"=>"Paperback", "binding"=>"Paperback", "published_date"=>"2008-01-25", "image"=>"http://ecx.images-amazon.com/images/I/41n-JSlBHkL._SL75_.jpg" }, "label"=>{ "name"=>"Scheduleman Tartan", "plid"=>"1709" } } CampusBooks::Base.expects(:get).once.returns({ "response" => expected_response }) actual_response = CampusBooks::Base.get_response('/bookinfo', :query => { :isbn => '9780596516178' }) assert_equal expected_response, actual_response end should "raise an exception when an API error occurs" do CampusBooks::Base.expects(:get).once.returns({ "response" => { "status" => "error", "errors" => { "error" => [ "Permission Denied - Invalid or missing API Key", "'isbn' parameter is required", "'' is not a valid ISBN", "Unable to create a book with isbn " ] }, "version" => "3" } }) exception = assert_raise CampusBooks::Error do CampusBooks::Base.get_response('/bookinfo', :query => { :isbn => '' }) end assert_equal %Q{4 errors occured while getting path '/bookinfo' with options {:query=>{:isbn=>""}}: Permission Denied - Invalid or missing API Key 'isbn' parameter is required '' is not a valid ISBN Unable to create a book with isbn }, exception.message end end
class Trinary def initialize(tri_string) @trinary = tri_string end def to_decimal return 0 if @trinary.match(/[^012]/) total = 0 @trinary.chars.reverse.each_with_index do |digit, index| if index == 0 total += digit.to_i else total += digit.to_i * (3**index) end end total end end # class Trinary end
# Show new_potluck form. get "/new_potluck" do erb :"potlucks/new_potluck" end # Process new_potluck form. post "/new_potluck" do @potluck = Potluck.new(:name => params[:potluck_name]) if @potluck.save redirect "/" else erb :"potlucks/new_potluck" end end # This route shows the edit_potluck form. Which potlucks is it editing? Its editing the potluck with ID :potluck_id. get "/edit_potluck/:potluck_id" do @potluck = Potluck.find_by_id(params[:potluck_id]) @potluck_items = @potluck.items erb :"potlucks/edit_potluck" end # This route processes the submitted edit_potluck form. Once again, it finds the potluck by its ID... post "/edit_potluck/:potluck_id" do @potluck = Potluck.find_by_id(params[:potluck_id]) @potluck.update_attributes(:status => params[:potluck_status]) if @potluck.update_attributes(params[:potluck]) redirect "/" else erb :"potlucks/edit_potluck" end end
SwellBot::Engine.routes.draw do resources :bot_inputs root to: 'bot_inputs#index' end
name 'uru' maintainer 'Evan Machnic' maintainer_email 'emachnic@gmail.com' license 'All rights reserved' description 'Installs/Configures uru' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.2.0' recipe 'uru', 'Downloads the Uru binary for the server platform and installs in specified directory' recipe 'uru::unix', 'Downloads the Uru binary archive and unpacks the "uru_rt" executable file' recipe 'uru::install', 'Installs Uru depending on the platform' recipe 'uru::upgrade', 'Removes the old "uru_rt" executable if found' depends 'tar', '~> 0.0.4' attribute 'uru/username', display_name: 'Uru Username', description: 'Username that Uru will run under', type: 'string', required: 'required' attribute 'uru/home_dir', display_name: 'Uru Home Directory', description: 'Home directory of the Uru Username', type: 'string', required: 'required' attribute 'uru/action', display_name: 'Uru Action', description: 'Way to run the Uru cookbook', type: 'string', choice: [ 'install', 'upgrade' ], required: 'required', default: 'install' attribute 'uru/version', display_name: 'Uru Version', description: 'Version of Uru to install', type: 'string', required: 'required', default: '0.6.4' attribute 'uru/src_url', display_name: 'Uru Source URL', description: 'URL for Uru downloads', type: 'string', required: 'required', default: 'http://downloads.sourceforge.net/project/urubinaries/uru/#{node["uru"]["version"]}/' attribute 'uru/src_filename', display_name: 'Uru Source Filename', description: 'Filename of the Uru binary package', type: 'string', required: 'required', default: 'uru-#{node["uru"]["version"]}-#{platform}-x86.#{extension}'