text
stringlengths
10
2.61M
class ManageIQ::Providers::Amazon::CloudManager::CloudDatabase < ::CloudDatabase supports :create supports :delete def self.params_for_create(ems) { :fields => [ { :component => 'text-field', :id => 'name', :name => 'name', :label => _('Cloud Database Name'), :isRequired => true, :validate => [{:type => 'required'}], }, { :component => 'text-field', :name => 'storage', :id => 'storage', :label => _('Storage (in Gigabytes)'), :type => 'number', :step => 1, :isRequired => true, :validate => [{:type => 'required'}, {:type => 'min-number-value', :value => 1, :message => _('Size must be greater than or equal to 1')}], }, { :component => 'select', :name => 'flavor', :id => 'flavor', :label => _('Cloud Database Instance Class'), :includeEmpty => true, :isRequired => true, :validate => [{:type => 'required'}], :options => ems.cloud_database_flavors.active.map do |db| { :label => db[:name], :value => db[:name], } end, }, { :component => 'select', :name => 'database', :id => 'database', :label => _('Cloud Database'), :includeEmpty => true, :isRequired => true, :validate => [{:type => 'required'}], :options => ["aurora", "aurora-mysql", "aurora-postgresql", "mariadb", "postgres", "mysql", "oracle-ee", "oracle-ee-cdb", "oracle-se2", "oracle-se2-cdb", "sqlserver-ee", "sqlserver-se", "sqlserver-ex", "sqlserver-web"].map do |db| { :label => db, :value => db, } end, }, { :component => 'text-field', :id => 'username', :name => 'username', :label => _('Master Username'), :isRequired => true, :validate => [{:type => 'required'}], }, { :component => 'password-field', :type => 'password', :id => 'password', :name => 'password', :label => _('Master Password'), :isRequired => true, :validate => [{:type => 'required'}], }, ], } end def self.raw_create_cloud_database(ext_management_system, options) options.symbolize_keys! ext_management_system.with_provider_connection(:service => :RDS) do |connection| connection.client.create_db_instance(:db_instance_identifier => options[:name], :db_instance_class => options[:flavor], :allocated_storage => options[:storage], :engine => options[:database], :master_username => options[:username], :master_user_password => options[:password]) end rescue => e _log.error("cloud_database=[#{name}], error: #{e}") raise end def raw_delete_cloud_database with_provider_connection(:service => :RDS) do |connection| connection.client.delete_db_instance(:db_instance_identifier => name, :skip_final_snapshot => true) end rescue => err _log.error("cloud database=[#{name}], error: #{err}") raise end end
class AddEmployeeToProgressReports < ActiveRecord::Migration def change add_column :progress_reports, :employee_id, :integer end end
FactoryGirl.define do factory :user do name { Faker::Name.name } title "Worker" photo_url "http://placekitten.com/g/200/300" email { Faker::Internet.email} password "winner" password_confirmation "winner" end trait :superuser do superuser true end end
require 'net/http' require 'json' require 'map' require "erb" require 'weather-api/astronomy' require 'weather-api/atmosphere' require 'weather-api/condition' require 'weather-api/forecast' require 'weather-api/location' require 'weather-api/response' require 'weather-api/units' require 'weather-api/utils' require 'weather-api/wind' require 'weather-api/error.rb' module WeatherApi class << self VALID_TEMP_UNITS = [Units::CELSIUS, Units::FAHRENHEIT].freeze # https://developer.yahoo.com/weather/ API_ENDPOINT = ENV['YAHOO_WEATHER_API_ENDPOINT'].freeze def search_by_woeid(woeid, unit = Units::CELSIUS) get_response(unit, "?q=select * from weather.forecast where woeid='#{woeid}' and u='#{unit}'&format=json", woeid) end def search_by_city_name(city_name, unit = Units::CELSIUS) get_response(unit, "?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='#{city_name}') and u='#{unit}'&format=json", city_name) end private def get url uri = URI.parse url res = Net::HTTP.get_response(uri) response = res.body.to_s response = Map.new(JSON.parse(response))[:query][:results][:channel] if response.nil? || res.code != '200' raise Error.new("500"), "Failed to get weather [url=#{url}]." end response rescue => e raise Error.new("500"), "Failed to get weather [url=#{url}, e=#{e}]." end def valid_unit(unit) unless VALID_TEMP_UNITS.include?(unit) raise Error.new("400"), "Invalid temperature unit" end end def get_response(unit, query, location) valid_unit(unit) url = API_ENDPOINT + URI.escape(query) doc = get url Response.new location, url, doc end end end
class SpeakersController < ApplicationController before_action :authenticate_admin!, except: [:index, :show] before_action :set_speaker, only: [:show, :edit, :update, :destroy] before_action :get_areas, only: [:new, :edit, :index] layout 'admin', only: [:new, :edit] # GET /speakers # GET /speakers.json def index @speakers = Speaker.order :last_name end # GET /speakers/1 # GET /speakers/1.json def show @similar_speakers = Speaker.ransack(areas_title_cont_any: @speaker.area_titles).result(distinct: true).sample(3) end # GET /speakers/new def new @speaker = Speaker.new end # GET /speakers/1/edit def edit end # POST /speakers # POST /speakers.json def create @speaker = Speaker.new(speaker_params) respond_to do |format| if @speaker.save save_related_objects format.html { redirect_to @speaker, notice: 'Speaker was successfully created.' } format.json { render :show, status: :created, location: @speaker } else format.html { render :new } format.json { render json: @speaker.errors, status: :unprocessable_entity } end end end # PATCH/PUT /speakers/1 # PATCH/PUT /speakers/1.json def update respond_to do |format| if @speaker.update(speaker_params) save_related_objects format.html { redirect_to @speaker, notice: 'Speaker was successfully updated.' } format.json { render :show, status: :ok, location: @speaker } else format.html { render :edit } format.json { render json: @speaker.errors, status: :unprocessable_entity } end end end # DELETE /speakers/1 # DELETE /speakers/1.json def destroy @speaker.destroy respond_to do |format| format.html { redirect_to speakers_url, notice: 'Speaker was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_speaker @speaker = Speaker.friendly.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def speaker_params params.require(:speaker).permit(:name, :last_name, :email, :description, :information, :twitter, :avatar, :visible_on_home) end def get_areas @areas = Area.order(:title) end def save_related_objects case params['speaker_images_save_method'] when 'add', 'replace', 'destroy' speaker_images_save_method = params['speaker_images_save_method'] else speaker_images_save_method = 'replace' end if params['speaker_images'] or speaker_images_save_method == 'destroy' if speaker_images_save_method == 'replace' or speaker_images_save_method == 'destroy' @speaker.speaker_images.each do |image| image.destroy end end if speaker_images_save_method == 'replace' or speaker_images_save_method == 'add' params['speaker_images'].each do |image| @speaker.speaker_images.create(image: image) end end end if params['speaker_videos'] and params['speaker_videos'].first.present? video_urls = [] @speaker.speaker_videos.each do |video| video_urls << video.url unless params['speaker_videos'].include? video.url video.destroy end end params['speaker_videos'].each do |video| unless video_urls.include? video or not video.include? 'https://www.youtube.com/watch?v=' @speaker.speaker_videos.create(url: video) end end elsif not @speaker.speaker_videos.blank? @speaker.speaker_videos.each do |v| v.destroy end end if params['speaker_areas'] and params['speaker_areas'].first.present? sp_area_titles = [] @speaker.speaker_areas.each do |spa| sp_area_titles << spa.area.title unless params['speaker_areas'].include? spa.area.title spa.destroy end end params['speaker_areas'].each do |param| unless sp_area_titles.include? param a = Area.new(title: param) unless a.save a = Area.find_by(title: param) end @speaker.speaker_areas.create(area: a) end end elsif not @speaker.speaker_areas.blank? @speaker.speaker_areas.each do |a| a.destroy end end end end
class ChartStatus attr_accessor :song, :rank, :weeks_charted, :peak_position, :previous_week def initialize(song_info) @rank = song_info[:rank].to_i @previous_week = song_info[:previous_week].to_i @peak_position = song_info[:peak_position].to_i @weeks_charted = song_info[:weeks_charted].to_i end def self.new_songs Song.all.select { | song | song.previous_week == "--" } end def is_new? previous_week == "--" end def position_change if previous_week > rank puts "#{song.title} moved up from \##{previous_week} to \##{rank}!" elsif previous_week < rank puts "#{song.title} moved down from \##{previous_week} to \##{rank}." elsif previous_week == rank puts "#{song.title} remained at #{rank}." end end def peak_status if rank == peak_position puts "It's currently at it's peak position!!" else puts "It's down from it's peak position, which was number #{peak_position}." end end def weeks_status puts "#{song.title} has been on the charts for #{weeks_charted} weeks." end end
require "pg" class SessionPersistence def initialize(session) @session = session @session[:lists] ||= [] end def find_list(list_id) @session[:lists].find { |list| list[:id] == list_id } if list_id end def all_lists @session[:lists] end def create_new_list(list_name) id = next_item_id(@session[:lists]) @session[:lists] << { id: id, name: list_name, todos: [] } end def delete_list(list_id) @session[:lists].reject! { |list| list[:id] == list_id } end def update_list_name(list_id, new_name) list = find_list(list_id) list[:name] = new_name end def create_new_todo(list_id, todo_item) list = find_list(list_id) id = next_item_id(list[:todos]) list[:todos] << { id: id, name: todo_item, completed: false } end def delete_todo_from_list(list_id, todo_id) list = find_list(list_id) todos = list[:todos] todos.reject! { |todo| todo[:id] == todo_id } end def update_todo_status(list_id, todo_id, new_status) list = find_list(list_id) todo = list[:todos].find { |todo| todo[:id] == todo_id } todo[:completed] = new_status end def mark_all_todos_as_completed(list_id) list = find_list(list_id) list[:todos].each do |todo| todo[:completed] = true end end private def next_item_id(items) max = items.map { |item| item[:id] }.max || 0 max + 1 end end
require 'spec_helper' describe Movie do describe "#similar" do it "should find movies by the same director" do @Test_Movies = [ double("Movie", :id => 1, :title => "Star Wars", :director => "George Lucas"), double("Movie", :id => 2, :title => "THX-1138", :director => "George Lucas"), double("Movie", :id => 3, :title => "Blade Runner", :director => "Ridley Scott") ] results = Movie.search_directors(@Test_Movies[0].director) expect(@Test_Movies[0].title).to eq("Star Wars") expect(@Test_Movies[1].title).to eq('THX-1138') end it "should not find movies by different directors" do @Test_Directors = [ double("Movie", :id => 1, :title => "Star Wars", :director => "George Lucas"), double("Movie", :id => 2, :title => "THX-1138", :director => "George Lucas"), double("Movie", :id => 3, :title => "Blade Runner", :director => "Ridley Scott") ] expect(Movie.search_directors(@Test_Directors[2].title)).not_to eq("Blade Runner") end end describe '#ratings' do it 'returns all ratings' do expect(Movie.all_ratings).to match(%w(G PG PG-13 NC-17 R)) end end end
class PrivacyPolicy < ActiveRecord::Base validates_presence_of :content end # == Schema Information # # Table name: privacy_policies # # id :integer not null, primary key # content :text #
class AddSecurityExtensionsToAdminUsers < ActiveRecord::Migration def change add_column :admin_users, :role, :integer, index: true # password expirable add_column :admin_users, :password_changed_at, :datetime, index: true # session limitable add_column :admin_users, :unique_session_id, :string, limit: 20 # expirable add_column :admin_users, :last_activity_at, :datetime, index: true add_column :admin_users, :expired_at, :datetime, index: true # lockable add_column :admin_users, :failed_attempts, :integer, default: 0 add_column :admin_users, :unlock_token, :string add_column :admin_users, :locked_at, :datetime end end
class ChangeEventLabtimeYrToLabtimeYear < ActiveRecord::Migration def change rename_column :events, :labtime_hr, :labtime_hour end end
class UsersController < ApplicationController before_action :authenticate_user! before_action :set_user def show @followers = @user.followers @following = @user.following @follower = @followers.find_by(followed_by_id: current_user.id) end private def set_user @user = User.find(params[:id]) end end
class AddNotificationToMessage < ActiveRecord::Migration[5.2] def change add_reference :messages, :post_event, foreign_key: true end end
class RegistrationsController < Devise::RegistrationsController layout 'application_base' def new @user = User.new @user = User::RegistrationForm.new(@user) end def create @user = User.new @user = User::RegistrationForm.new(@user) if @user.validate(new_user_params) && @user.save @user = @user.model if resource.active_for_authentication? set_flash_message! :notice, :signed_up sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}" expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource set_minimum_password_length render action: :new end end def edit @user = User::MyAccountForm.new(current_user) end def update @user = User::MyAccountForm.new(current_user) if @user.validate(edit_user_params) && @user.save redirect_to members_area_path, notice: 'Account updated' else render action: :edit end end private def new_user_params params.require(:user).permit(:email, :phone, :first_name, :last_name, :address_line_1, :address_line_2, :address_line_3, :city, :region, :postcode, :country, :password, :password_confirmation) end def edit_user_params params[:user].delete(:password) if params[:user][:password].blank? params[:user].delete(:password_confirmation) if params[:user][:password_confirmation].blank? params.require(:user).permit(:email, :phone, :first_name, :last_name, :address_line_1, :address_line_2, :address_line_3, :city, :region, :postcode, :password, :password_confirmation, :teacher, :teacher_email, :teacher_phone, :teaching_locations, :current_password) end end
# Describes a Player who can play in a game class PlayerController < ApplicationController def index @player_data = data.to_json respond_to do |format| format.html { render } format.json { render json: data } end end def update player = data player_params = params['player'] player.update(player_params.to_hash) render json: data end private def data Player.select(:id, :first_name, :last_name).last end end
# Yeah, I probably shouldn't use Ruby for this, but I'm lazy. require "mustache" require "rake" IDIOMATIC_TYPE_NAMES = { "Boolean" => "bool", "Byte" => "byte", "Int16" => "short", "UInt16" => "ushort", "Int32" => "int", "UInt32" => "uint", "Int64" => "long", "UInt64" => "ulong", "Single" => "float", "Double" => "double", "Decimal" => "decimal", "DateTime" => "DateTime", "TimeSpan" => "TimeSpan" } desc "Generate C# source files for Parser classes" task :generate do template = File.read(File.expand_path("./templates/SpecificTypeParser.cs.mustache")) IDIOMATIC_TYPE_NAMES.each do |type, name| generated_source = Mustache.render(template, { :type => type, :name => name }) puts "Writing #{type}Parser.cs..." File.open("#{type}Parser.cs", "w") do |f| f.write(generated_source) end end template = File.read(File.expand_path("./templates/Parser.cs.mustache")) generated_source = Mustache.render(template, { :types => IDIOMATIC_TYPE_NAMES.keys }) puts "Writing Parser.cs..." File.open("Parser.cs", "w") do |f| f.write(generated_source) end puts "Done." end task :default => :generate
class Workspace < ActiveRecord::Base validates_presence_of :game_board_id, :user_id belongs_to :user end
require 'rspec' require_relative 'combination.rb' describe 'combination' do context 'RoyalFlush' do it 'should do 1' do expect(Combination.royal_flush([1, 14, 48, 49, 50, 51, 52], 0)).to eq(1) end end context 'StraightFlush' do it 'should do 1' do expect(Combination.straight_flush([1, 14, 47, 48, 49, 50, 51], 0)).to eq(1) end end context 'Quads' do it 'should do 1' do expect(Combination.quads([1, 14, 27, 40, 41, 43, 45], 0)).to eq(1) end end context 'FullHouse' do it 'should do 1' do expect(Combination.full_house([1, 14, 27, 28, 41, 43, 44], 0)).to eq(1) end end context 'Straight' do it 'should do 1' do expect(Combination.straight([1, 15, 29, 43, 44, 50, 51], 0)).to eq(1) end end context 'Flush' do it 'should do 1' do expect(Combination.flush([1, 3, 5, 7, 9, 32, 45], 0)).to eq(1) end end context 'Set' do it 'should do 1' do expect(Combination.set([1, 14, 27, 39, 41, 43, 45], 0)).to eq(1) end end context 'TwoPairs' do it 'should do 1' do expect(Combination.two_pair([1, 14, 28, 30, 41, 48, 50], 0)).to eq(1) end end context 'OnePair' do it 'should do 1' do expect(Combination.one_pair([1, 14, 23, 30, 41, 48, 51], 0)).to eq(1) end end end
require File.expand_path('../spec/environment', __FILE__) require 'rake/rdoctask' require 'rake/testtask' require 'spec/rake/spectask' desc "Build a gem file" task :build do system "gem build mail.gemspec" end task :default => :spec Spec::Rake::SpecTask.new(:rcov) do |t| t.spec_files = FileList['test/**/tc_*.rb', 'spec/**/*_spec.rb'] t.rcov = true t.rcov_opts = t.rcov_opts << ['--exclude', '/Library,/opt,/System,/usr'] end Spec::Rake::SpecTask.new(:spec) do |t| t.warning = true t.spec_files = FileList["#{File.dirname(__FILE__)}/spec/**/*_spec.rb"] t.spec_opts = %w(--backtrace --diff --color) t.libs << "#{File.dirname(__FILE__)}/spec" t.libs << "#{File.dirname(__FILE__)}/spec/mail" end Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'Mail - A Ruby Mail Library' rdoc.options << '-c' << 'utf-8' rdoc.options << '--line-numbers' rdoc.options << '--inline-source' rdoc.options << '-m' << 'README.rdoc' rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') rdoc.rdoc_files.include('lib/network/**/*.rb') rdoc.rdoc_files.exclude('lib/parsers/*') end # load custom rake tasks Dir["#{File.dirname(__FILE__)}/lib/tasks/**/*.rake"].sort.each { |ext| load ext }
# Build a program that asks a user for the length and width of a room in meters and then displays the area of the room in both square meters and square feet. # Note: 1 square meter == 10.7639 square feet # Do not worry about validating the input at this time. # Example Run # Enter the length of the room in meters: # 10 # Enter the width of the room in meters: # 7 # The area of the room is 70.0 square meters (753.47 square feet). # Question: # Write a method that takes two inputs from a user then outputs a string # Explicit vs Implicit # Explicit: # 1. 1 square meter is 10.7639 square feet # 2. to get user input, it's gets.chomp # Implicit: # N/A # Input vs Output # Input: 2 integers # Output: String # Algorithm: # area_room method # 1. set a constant 'SQFT' to 10.7639. This will be the conversion rate between square feet and square meter # 2. set variable 'length' to user input using gets.chomp method and convert it to float using to_f # 3. set variable 'width' to user input using gets.chomp method and convert it to float using to_f # 4. initialize a variable 'area_meter' to the product of 'length' and 'width' # 5. initialize a variable 'area_feet' to the product of 'area_meter' and constant 'SQFT' # 6. Use string interpolation and print out statement # def area_room # SQFT = 10.7639 # length = gets.chomp.to_f # width = gets.chomp.to_f # area_meter = length * width # area_feet = area_meter * SQFT # puts "The area of the room is #{area_meter} meters, or #{area_feet} feet." # end
require "rspec" require_relative "../lib/board" describe "Remaining seeds" do it "should count the number of remaining seeds on one side of the board" do Board.new(4).remaining_seeds.should eq 24 Board.new(5).remaining_seeds.should eq 30 Board.new(6).remaining_seeds.should eq 36 end end describe "Flip board" do let(:board) { Board.new(0, [0, 0, 0, 0, 4, 4, 4, 0, 4, 4, 4, 0, 0, 0]) } it "should turn the board around 180 degrees" do board.remaining_seeds.should eq 24 board.flip.remaining_seeds.should eq 0 board = Board.new(0, [0, 2, 0, 4, 0, 4, 4, 0, 4, 4, 4, 0, 0, 0]) board.remaining_seeds.should eq 20 board.flip.remaining_seeds.should eq 6 end end describe "Sow seeds" do let(:board) { Board.new(0, [0, 0, 0, 0, 4, 4, 4, 0, 4, 4, 4, 0, 0, 0]) } it "should sow seeds from a given house in a counter-clockwise direction" do board.remaining_seeds.should eq 24 board.sow_seeds_from 4 board.remaining_seeds.should eq 24 - 4 board.flip.remaining_seeds.should eq 4 board.sow_seeds_from 5 board.remaining_seeds.should eq 17 board.flip.remaining_seeds.should eq 7 end it "should steal seeds from opposing house if last seed lands in an empty house" do board.remaining_seeds.should eq 24 board.sow_seeds_from 4 board.sow_seeds_from 8 board.remaining_seeds.should eq 24 - 4 + 1 end it "should return :done after sowing seeds and there are still seeds remaining in other houses" do board.sow_seeds_from(4).should eq :done end it "should return :game_over if all houses are empty after sowing" do board.sow_seeds_from(4).should_not eq :game_over board.sow_seeds_from 10 board.sow_seeds_from 9 board.sow_seeds_from 8 board.sow_seeds_from 6 board.sow_seeds_from 5 board.sow_seeds_from(4).should eq :game_over end it "should return :again if the last seed lands in the store" do board = Board.new(0, [0, 0, 0, 0, 4, 4, 4, 0, 1, 2, 4, 0, 0, 0]) board.sow_seeds_from(8).should eq :again board.sow_seeds_from(9).should eq :again board.sow_seeds_from(10).should_not eq :again end end
class DamageImmunitiesController < ApplicationController before_action :set_damage_immunity, only: [:show, :edit, :update, :destroy] before_action :is_admin, only: [:edit, :update, :destroy] # GET /damage_immunities # GET /damage_immunities.json def index @damage_immunities = DamageImmunity.all end # GET /damage_immunities/1 # GET /damage_immunities/1.json def show end # GET /damage_immunities/new def new @damage_immunity = DamageImmunity.new end # GET /damage_immunities/1/edit def edit end # POST /damage_immunities # POST /damage_immunities.json def create @damage_immunity = DamageImmunity.new(damage_immunity_params) respond_to do |format| if @damage_immunity.save format.html { redirect_to @damage_immunity, notice: 'Damage immunity was successfully created.' } format.json { render :show, status: :created, location: @damage_immunity } else format.html { render :new } format.json { render json: @damage_immunity.errors, status: :unprocessable_entity } end end end # PATCH/PUT /damage_immunities/1 # PATCH/PUT /damage_immunities/1.json def update respond_to do |format| if @damage_immunity.update(damage_immunity_params) format.html { redirect_to @damage_immunity, notice: 'Damage immunity was successfully updated.' } format.json { render :show, status: :ok, location: @damage_immunity } else format.html { render :edit } format.json { render json: @damage_immunity.errors, status: :unprocessable_entity } end end end # DELETE /damage_immunities/1 # DELETE /damage_immunities/1.json def destroy @damage_immunity.destroy respond_to do |format| format.html { redirect_to damage_immunities_url, notice: 'Damage immunity was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_damage_immunity @damage_immunity = DamageImmunity.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def damage_immunity_params params.fetch(:damage_immunity).permit(:name) end end
class RecordingSerializer < ActiveModel::Serializer attributes :id, :temp, :status belongs_to :location end
# Модель дополнительного email-а class AdditionalEmail < ActiveRecord::Base include Models::Limitable belongs_to :user validates :user, :email, presence: true attr_accessible :email attr_accessible :email, as: :admin end
# frozen_string_literal: true describe Grape::ExtraValidators::MaximumValue do module ValidationsSpec module MaximumValueValidatorSpec class API < Grape::API default_format :json params do optional :static_number, type: Integer, maximum_value: 10 optional :maximum_value_for_proc_number, type: Integer, allow_blank: false optional :proc_number, type: Integer, maximum_value: ->(params) { params[:maximum_value_for_proc_number] + 1 } end post "/" do body false end end end end def app ValidationsSpec::MaximumValueValidatorSpec::API end let(:params) do { static_number: static_number, maximum_value_for_proc_number: maximum_value_for_proc_number, proc_number: proc_number, }.compact end let(:static_number) { nil } let(:maximum_value_for_proc_number) { nil } let(:proc_number) { nil } before { post "/", params } subject { last_response.status } context "when a configured maximum value is a static value" do context "the value is less than the maximum value" do let(:static_number) { 9 } it { is_expected.to eq(204) } end context "the value is equal to the maximum value" do let(:static_number) { 10 } it { is_expected.to eq(204) } end context "the value is more than the maximum value" do let(:static_number) { 11 } it { is_expected.to eq(400) } end end context "when a configured maximum value is a Proc" do context "the value is less than the maximum value" do let(:maximum_value_for_proc_number) { 10 } let(:proc_number) { 10 } it { is_expected.to eq(204) } end context "the value is equal to the maximum value" do let(:maximum_value_for_proc_number) { 10 } let(:proc_number) { 11 } it { is_expected.to eq(204) } end context "the value is more than the maximum value" do let(:maximum_value_for_proc_number) { 10 } let(:proc_number) { 12 } it { is_expected.to eq(400) } end end context "when the parameter is nil" do let(:params) { {} } it { is_expected.to eq(204) } end end
# -*- coding: utf-8 -*- class OmniauthCallbacksController < Devise::OmniauthCallbacksController include Devise::Controllers::Rememberable include ApplicationHelper ## # Handle authentication from Google OAuth 2.0. def google_oauth2 process_login end ## # Handle authentication from Twitter def twitter process_login end ## # Handle authentication from Yahoo def yahoo process_login end ## # Handle authentication from LinkedIn def linkedin process_login end ## # Handle authentication from facebook def facebook process_login end ## # Handle authentication from Northwestern Medicine def northwestern_medicine process_login end def process_login auth = request.env['omniauth.auth'] log_request("[process_login] auth: #{auth.inspect}") # Here we check to see if we did get back an OmniAuth::AuthHash # or something that responds to :[] # Sometimes we are getting back true:TrueClass - still don't know the cause of that if auth.respond_to?(:[]) && auth['info'].respond_to?(:[]) @user = User.find_for_oauth(auth, current_user) if @user.persisted? sign_in_and_redirect @user, event: :authentication set_session_attributes(@user, auth) check_session remember_me(@user) if params['remember_me'].to_i == 1 flash[:notice] = I18n.t('login.authentication_success_via', provider: provider_name(auth['provider'])) else session["devise.#{provider}_data"] = env["omniauth.auth"] redirect_to new_user_registration_url end else # And in the case of receiving true - simply redirect the user to the login page Rails.logger.error("~~~ [process_login] OmniAuth::AuthHash not found redirecting to new_user_session_path") redirect_to new_user_session_path, flash: { error: I18n.t('login.authentication_failure') } end end ## # Given a provider make a pretty presentation of the # provider name. # @param [String, Symbol, nil] # @return [String] def provider_name(provider) # Set var to String as default action is to call # titleize on the given parameter provider = provider.to_s case provider when 'google_oauth2' provider = 'Google' when 'linkedin' provider = 'LinkedIn' when 'northwestern_medicine', 'nu', 'nmff-net', 'nmh', 'nmff' provider = 'Northwestern Medicine' else provider = provider.titleize end provider end # def after_sign_in_path_for(resource) # if resource.email_verified? # super resource # else # finish_signup_path(resource) # end # end end
#============================================================================== # ** Game_Enemy #------------------------------------------------------------------------------ # This class handles enemies. It used within the Game_Troop class # ($game_troop). #============================================================================== class Game_Enemy < Game_Battler #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_accessor :level attr_accessor :rank #------------------------------------------------------------------------ # * Set hashid #------------------------------------------------------------------------ def hash_self @hashid = enemy.hashid + self.hash super end #-------------------------------------------------------------------------- # * Overwrite: Object Initialization #-------------------------------------------------------------------------- def initialize(index, enemy_id) super() @index = index @enemy_id = enemy_id enemy = $data_enemies[@enemy_id] @original_name = enemy.name @letter = "" @plural = false @screen_x = 0 @screen_y = 0 @battler_name = enemy.battler_name @battler_hue = enemy.battler_hue @level = 1 case enemy.note when /<Chief>/i; @rank = :chief; when /<Captain>/i; @rank = :captain; when /<Elite>/i; @rank = :elite; when /<Minion>/i; @rank = :minion; when /<Critter>/i; @rank = :critter; else @rank = :minion end @level = enemy.note =~ /<Level = (\d+)>/i ? $1.to_i : 1.to_i unless enemy.nil? @event = nil setup_dnd_battler(enemy) init_skills @skills << get_learned_skills @hp = mhp @mp = mmp end #-------------------------------------------------------------------------- alias :is_a_obj? :is_a? def is_a?(cls) return is_a_obj?(cls) || enemy.is_a?(cls) end #-------------------------------------------------------------------------- def team_id @team_id = enemy.team_id if @team_id.nil? return @team_id end #-------------------------------------------------------------------------- def face_name return enemy.face_name end #-------------------------------------------------------------------------- def face_index return enemy.face_index end #--------------------------------------------------------------------------- def get_learned_skills enemy.actions.collect{|action| $data_skills[action.skill_id] } end #--------------------------------------------------------------------------- def skills @skills end #--------------------------------------------------------------------------- def weapon_ammo_ready?(weapon) return true end #--------------------------------------------------------------------------- def weapon_level_prof enemy.weapon_level_prof end #--------------------------------------------------------------------------- def secondary_weapon enemy.secondary_weapon end #-------------------------------------------------------------------------- # * Overwrite: Get Base Value of Parameter #-------------------------------------------------------------------------- def param_base(param_id) value = enemy.params[param_id] + super(param_id) return value if (value || 0).to_bool return DND::Base_Param[param_id] end #--------------------------------------------------------------------------- # * Method Missing # ---------------------------------------------------------------------- # DANGER ZONE: Redirect to Actor #--------------------------------------------------------------------------- def method_missing(symbol, *args) super(symbol, args) unless @map_char super(symbol, args) unless @map_char.methods.include?(symbol) @map_char.method(symbol).call(*args) end #--------------------------------------------------------------------------- def determine_skill_usage action_list = enemy.actions.select {|a| action_valid?(a) } return if action_list.empty? list = action_list.sort{|a, b| b.rating <=> a.rating} list.select!{|a| item_test(self, $data_skills[a.skill_id]) && usable?($data_skills[a.skill_id])} skill = $data_skills[list.first.skill_id] rescue nil return skill end #--------------------------------------------------------------------------- def load_tactic_commands @tactic_commands = TacticCommandModule.load_template(:basic, self) end end
class Customer < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable has_many :request has_many :payment has_many :comment has_many :schedule # Name no null validates :name , presence: true #Email no null validates :email , presence: true #User name no null validates :user_name, presence: true # Password no null validates :encrypted_password , presence: true # Validate associate #Para la integracion de google maps geocoded_by :address #Puede ser una direccion ip tambien (ojo con esto) after_validation :geocode has_attached_file :picture, styles: { medium: "400x400>", thumb: "100x100>" }, default_url: "/defauls_user_img.png" validates_attachment_content_type :picture, content_type: /\Aimage\/.*\z/ devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable devise :omniauthable, :omniauth_providers => [:facebook] #----------------------QUERIES #Deviuelve una colecion de las peticiones echas por el cliente actual y los detalles def tecnicos_postulados coleccion = [] self.request.each do |request| info = {} info[:id] = request.id info[:article] = request.article info[:servicio] = request.service.description info[:tecnicos] = request.proposal coleccion.append(info) end coleccion end #----------------------OMNIAUTH def self.new_with_session(params, session) super.tap do |customer| if data = session["devise.facebook"] && session["devise.facebook"]["extra"]["raw_info"] customer.email = data["email"] if customer.email.blank? end end end ##def self.from_omniauth(auth) def self.from_facebook(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |customer| #where(facebook_id: auth.uid).first_or_create do |customer| customer.email = auth.info.email customer.name = auth.info.name customer.user_name = auth.info.email.split('@')[0] customer.password = Devise.friendly_token[0,20] customer.skip_confirmation! # customer.name = auth.info.name # assuming the user model has a name end end end
require 'spec_helper' describe Zertico::Service do let(:admin_service) { Admin::UserService.new } let(:gifts_service) { Person::GiftsService.new } let(:profile_service) { Person::ProfileService.new } let(:object) { Object.new } let(:users_service) { UsersService.new } let(:user) { User.new } before :each do User.stub(:new => user) end describe '#index' do it 'should return a collection of users' do users_service.index.should == [user, user] end before :each do users_service.index end it 'should save the collection in an instance variable' do users_service.users.should == [user, user] end end describe '#new' do it 'should return a new user' do users_service.new.should == user end before :each do users_service.new end it 'should save the user in an instance variable' do users_service.user.should == user end end describe '#show' do it 'should search for an user' do users_service.show({ :id => 1 }).should == user end before :each do users_service.show({ :id => 1 }) end it 'should save the user found in an instance variable' do users_service.user.should == user end end describe '#create' do it 'should search for an user' do users_service.create({ :user => {} }).should == user end before :each do users_service.create({ :user => {} }) end it 'should save the created user in an instance variable' do users_service.user.should == user end end describe '#update' do it 'should search for an user' do users_service.update({ :id => 1, :user => {} }).should == user end before :each do users_service.update({ :id => 1, :user => {} }) end it 'should update the user' do users_service.user.updated.should == true end it 'should save the updated user in an instance variable' do users_service.user.should == user end end describe '#destroy' do it 'should search for an user' do users_service.destroy({ :id => 1 }).should == user end before :each do users_service.destroy({ :id => 1 }) end it 'should destroy the user' do users_service.user.destroyed.should == true end it 'should save the destroyed user in an instance variable' do users_service.user.should == user end end %w(index new edit create update show destroy).each do |method_name| describe "#responder_settings_for_#{method_name}" do it "should return the responder settings for #{method_name} action" do users_service.send("responder_settings_for_#{method_name}").should == {} end end end describe '#resource_source' do context 'without a custom resource defined on class' do it 'should return it!' do users_service.resource_source.should == User end end context 'with a custom resource defined on class' do before :each do UsersService.resource_source = [ Person::Profile ] end it 'should return it!' do users_service.resource_source.should == Person::Profile end end end describe '#interface_id' do context 'on a pluralized service' do it 'should return id' do users_service.send(:interface_id).should == 'id' end end context 'on a namespaced service and interface model' do it 'should return id with the model name' do profile_service.send(:interface_id).should == 'person_profile_id' end end context 'on a namespaced service and non namespaced interface model' do it 'should return id with the model name' do admin_service.send(:interface_id).should == 'user_id' end end context 'on a non namespaced service and non namespaced interface model' do it 'should return id' do users_service.send(:interface_id).should == 'id' end end context 'on a namespaced service and an undefined interface model' do it 'should return id' do gifts_service.send(:interface_id).should == 'id' end end context 'when defined on class' do before :each do gifts_service.class.instance_variable_set('@interface_id', 'abc') end it 'should return the defined value' do gifts_service.send(:interface_id).should == 'abc' end end end describe '#interface_name' do it 'should return the interface name' do users_service.send(:interface_name).should == 'user' end context 'when defined on class' do before :each do gifts_service.class.instance_variable_set('@interface_name', 'abc') end it 'should return the defined value' do gifts_service.send(:interface_name).should == 'abc' end end end describe '#interface_class' do context 'on a pluralized service' do it 'should find the interface model' do users_service.send(:interface_class).should == User end end context 'on a namespaced service and interface model' do it 'should find the interface model' do profile_service.send(:interface_class).should == Person::Profile end end context 'on a namespaced service and non namespaced interface model' do it 'should find the interface model' do admin_service.send(:interface_class).should == User end end context 'on a non namespaced service and non namespaced interface model' do it 'should find the interface model' do users_service.send(:interface_class).should == User end end context 'when defined on class' do before :each do gifts_service.class.instance_variable_set('@interface_class', User) end it 'should return the defined value' do gifts_service.send(:interface_class).should == User end end end end
require 'rails_helper' describe 'External API request' do it 'Fetches energy xml data' do uri = URI('https://finestmedia.ee/kwh/') response = Net::HTTP.get(uri) expect(response).to be_an_instance_of(String) end end
require 'pry' class String def sentence? self.end_with?(".") end def question? self.end_with?("?") end def exclamation? self.end_with?("!") end def count_sentences split_self = self.split(".") split_self.delete_if { |chunk| chunk == "" } # binding.pry # Now we have an array split by periods with extra ones removed # binding.pry ["?","!"].each do |punctuation_mark| split_self.map! do |piece| piece.split(punctuation_mark) end # Flatten as many times as we need to while split_self[0].class == Array split_self.flatten! end # Delete the blank strings from the array split_self.delete_if { |chunk| chunk == "" } # binding.pry end # The length of the array should be the number of sentences split_self.length end end
class MailinglFormsController < ApplicationController before_action :set_mailingl_form, only: [:show, :edit, :update, :destroy] # GET /mailingl_forms # GET /mailingl_forms.json def index @mailingl_forms = MailinglForm.all end # GET /mailingl_forms/1 # GET /mailingl_forms/1.json def show render tv_shows_path end # GET /mailingl_forms/new def new @mailingl_form = MailinglForm.new(:subject => params[:subject], :body => params[:body]) end # GET /mailingl_forms/1/edit def edit end # POST /mailingl_forms # POST /mailingl_forms.json def create @mailingl_form = MailinglForm.new(mailingl_form_params) begin UserMailer.recommendation_email(mailingl_form_params).deliver rescue ArgumentError else redirect_to tv_shows_path, notice: 'Message has been sent.' end end # PATCH/PUT /mailingl_forms/1 # PATCH/PUT /mailingl_forms/1.json def update end # DELETE /mailingl_forms/1 # DELETE /mailingl_forms/1.json def destroy @mailingl_form.destroy respond_to do |format| format.html { redirect_to mailingl_forms_url, notice: 'Mailingl form was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_mailingl_form @mailingl_form = MailinglForm.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def mailingl_form_params params.require(:mailingl_form).permit(:subject, :body, :to) end end
require 'spec_helper' describe NationalHelper do context "#national?" do it "should return true when we do not have a centre ivar or center_id in the params" do expect(helper.national?).to be_true end it "should return false when we have a centre_id param" do helper.stub(:params).and_return centre_id: 'bondijunction' expect(helper.national?).to be_false end it "should return false when we have a centre ivar" do assign(:centre, true) expect(helper.national?).to be_false end end end
Given (/^I am on the Redfin search screen$/) do visit ('https://www.redfin.com/zipcode/97214') end When (/^I add a filter for a specific max price$/) do #this does not work if the More Filters button is selected before choosing a price select '$900k', from: 'quickMaxPrice' end When (/^I select the More Filters button$/) do page.find_button ('Filters') click_button ('Filters') end And (/^I add a filter for a min number of bedrooms$/) do select '2', from: 'minBeds' end And (/^I select house as the property type$/) do find('button[data-rf-test-name="uipt1"]').click find('button[data-rf-test-id="apply-search-options"]').click end Then (/^I should see three filter options applied to my search$/) do page.has_content?('$0-$900k, 2+ beds, house') end
class OfferDecorator < Decorator # Decorated Associations def decorated_supplier_purchase @decorated_supplier_purchase ||= SupplierPurchaseDecorator.new(decorated_object.supplier_purchase) end # End of Decorated Association delegate :ordered_from_supplier_at, to: :decorated_supplier_purchase, prefix: false, allow_nil: true def actual_specs @actual_specs ||= (self.supplier_order_actual_specs || self.specs) end def supplier_purchase_link if self.supplier_purchase link_to self.supplier_purchase_reference, print_supplier_purchase_path(self.supplier_purchase) else self.supplier_order_reference end end def supplier_order_reference off_ref = __getobj__.supplier_order_reference off_ref.blank? ? "Not Ordered" : off_ref end def request_unit __getobj__.request_unit.blank? ? 'Unit' : __getobj__.request_unit end def request @request ||= RequestDecorator.new(__getobj__.request) end # Takes options hash # quantity_class : class used for the quantity + uom span-label def display_specs(html_options = {}) html_options[:class] ||= 'label label-inverse' content_tag(:div) do inner = quantity_label(html_options[:class]) inner.safe_concat(' ') inner.safe_concat(self.specs) end end def display_actual_specs(text = "Actual:", html_options = {}) html_options[:class] ||= 'label label-important' if !__getobj__.supplier_order_actual_specs.blank? label = content_tag(:span, text, class: html_options[:class]) label.safe_concat(__getobj__.supplier_order_actual_specs) end end def display_summary @display_summary ||= summary || link_to('Please edit and add offer spec summary/code', edit_quote_path(__getobj__.quote)) end def quantity_label(label_class="") RequestDecorator.new(__getobj__.request).to_label(label_class) end def complete_quantity [ self.request_quantity.to_s, self.request_unit ].join(' ') end def display_status if self.supplier_order_delivered? "Delivered" elsif self.supplier_order_ordered_from_supplier? "Ordered" else "Not Ordered" end end # If Dollars # $40.00/unit # If PHP def display_selling_price str = number_to_currency(self.selling_price || 0, unit: self.currency) str = str + "/#{self.request_unit}" if !self.price_suffix.blank? str = str + " (#{self.price_suffix})" end str end def display_buying_price str = number_to_currency(self.buying_price || 0, unit: self.currency) str = str + "/#{self.request_unit}" if !self.price_suffix.blank? str = str + " (#{self.price_suffix})" end str end def display_total_buying_price str = number_to_currency(self.total_buying_price || 0, unit: Currency::LOCAL_CURRENCY) if !self.price_suffix.blank? str = str + " (#{self.price_suffix})" end str end def display_total_selling_price str = number_to_currency(self.total_selling_price || 0, unit: Currency::LOCAL_CURRENCY) if !self.price_suffix.blank? str = str + " (#{self.price_suffix})" end str end def price_suffix @suffix ||= [self.price_vat_status,self.price_basis].compact.join(" ") end def estimated_manufacture_end_date if date = __getobj__.supplier_order_estimated_manufactured_at date.to_date.to_s else display_none end end def actual_manufacture_end_date if date = __getobj__.supplier_order_manufactured_at date.to_date.to_s else display_none end end def estimated_delivery_date if date = __getobj__.supplier_order_estimated_delivered_at date.to_date.to_s else display_none end end def delivered_at if date = __getobj__.supplier_order_delivered_at date.to_date.to_s else display_none end end private def display_none 'None' end end
require_relative 'spec_helper' describe Teacher do before(:all) do raise RuntimeError, "be sure to run 'rake db:migrate' before running these specs" unless ActiveRecord::Base.connection.table_exists?(:teachers) end context '#name and #email' do before(:each) do @teacher = Teacher.new @teacher.assign_attributes( name: 'Happy', email: 'Gilmore@gmail.com', adress: '46 spadania ave', phone: '534-345-453' ) end it 'should have name and email methods' do [:name, :email].each { |method| expect(@teacher).to respond_to(method) } end end context 'validations' do before(:each) do @teacher1 = Teacher.new @teacher1.assign_attributes( name: 'Kreay', email: 'Shawn@gmail.com', adress: '46 spdania ave', phone: '(510) 555-1212 x4567' ) @teacher1.save end it 'should accept a unique info' do @teacher2 = Teacher.new @teacher2.assign_attributes( name: 'Kreay', email: 'Shawn@gmail.com', adress: '46 spdania ave', phone: '(510) 555-1212 x4567' ) @teacher2.save expect(@teacher2).to_not be_valid end end end
# # This program will generate .sql file from .xls / .xlsx file , and ready to upload to db # avoid direct connection with db , to reduce missing field value , etc. # # [created by Ary] # # \, A, wrong field value, '.0' require "roo" require "spreadsheet" require "nokogiri" filename = 'source_data_from_entry_team.xls' # source file @filename_target = 'import_outlets.sql' # target file sheet_index = 9 @cols_num = 23 # total column start from index zero. @col_notstrtype = ['enabled','city_id', 'neighbourhood_id', 'mall_id', 'latitude', 'longitude', 'price_id'] # column integer type @col_notstrtype_id= [] # column integer type index def generate2sql(w) File.open(@filename_target, 'w') {|file| file.write(w)} end def make_row(tmp, row, i) row.map {|w| break if row.index(w) > @cols_num tmp << append_quote(w.to_s, row.index(w), i) << "," } end def append_quote(w,idx, rowindex) w.gsub!(/\"|\\"/i, "\'") @col_notstrtype_id << idx if @col_notstrtype.include?(w) return (@col_notstrtype_id.include?(idx) && (rowindex>0)) || (rowindex==0) ? "#{w}" : "\"#{w.strip}\"" end def create_header(w) out = '' out << "INSERT INTO `outlets` " out << w.chomp(",\n") out << " VALUES " end # Main Spreadsheet.client_encoding = 'UTF-8' book = Spreadsheet.open filename sheet = book.worksheet sheet_index sql = "" puts "[#{DateTime.now}] Start..... " sheet.each_with_index do |row,i| tmp="" make_row(tmp, row, i) tmp.chomp!(",") sql += "(#{tmp}),\n" sql = create_header(sql.chomp(",")) if i == 0 end # generate sql file generate2sql(sql.chomp(",\n")) puts " [#{DateTime.now}] Generate....... file \"#{@filename_target}\" "
# extends acts_as_tree (closure_tree gem) # using 'position' property to sort w.r.t. siblings module Sortable extend ActiveSupport::Concern included do before_validation :set_position def set_position self.position ||= siblings.count end def <=>(other) position > other.position ? 1 : position < other.position ? -1 : 0 end def update_position(new_position) return if !new_position && position new_position = new_position.to_i if target = siblings.find_by(position: new_position) if siblings.count == new_position target.append_sibling(self) else target.prepend_sibling(self) end elsif target = siblings.sort[new_position] log "No sibling found with position #{new_position}.\nPrepending to '#{target.title}'" target.prepend_sibling(self) elsif siblings log "No sibling found with position #{new_position}.\nAppending to end." update(position: siblings.count) else update(position: 0) end end end end
require 'osx/cocoa' module Installd class Command include OSX def initialize(command) @command = command end def execute NSLog("Installd::Command: #{@command}") output = `#{@command} 2>&1` NSLog("Installd::Command: #{output}") unless $?.success? message = "Installd::Command: Error #{$?} executing: #{@command}" NSLog(message) raise message end return output end end end
require 'digest' require 'base64' module PaymentHelper def get_vtc_pay_url(order) order_code = order.code amount = order.sum sign = encrypt_array([ VTC_PAY_WEBSITE_ID, VTC_PAY_PAYMENT_METHOD, order_code, amount, VTC_PAY_RECEIVER_ACC, VTC_PARAM_EXTEND, VTC_PAY_SECRET ]) "#{VTC_PAY_BASE_URL}" + "?website_id=#{VTC_PAY_WEBSITE_ID}" + "&payment_method=#{VTC_PAY_PAYMENT_METHOD}" + "&order_code=#{order_code}" + "&amount=#{amount}" + "&receiver_acc=#{VTC_PAY_RECEIVER_ACC}" + "&param_extend=#{VTC_PARAM_EXTEND}" + "&sign=#{sign}" end def check_sign(status, order_code, amount, server_sign) server_sign == encrypt_array([ status, VTC_PAY_WEBSITE_ID, order_code, amount, VTC_PAY_SECRET ]) end def encrypt_array(arr) Digest::SHA256.hexdigest(arr.join("-")).upcase end end
class Admin::PagesController < AdminController def index @pages = PageQuery.all end def edit @page = PageQuery.find(params[:id]) end def update @page = PageQuery.find(params[:id]) if @page.update_attributes(params.require(:page).permit(:title)) flash[:success] = "Page \"#{@page.title}\" updated" redirect_to admin_pages_path() else render action: :edit end end def show @page_detail = PageDetail.build(self) end end
class BotUserType < DefaultObject description "Bot User type" implements GraphQL::Types::Relay::Node field :avatar, GraphQL::Types::String, null: true field :name, GraphQL::Types::String, null: true field :get_description, GraphQL::Types::String, null: true def get_description object.get_description end field :get_version, GraphQL::Types::String, null: true def get_version object.get_version end field :get_source_code_url, GraphQL::Types::String, null: true def get_source_code_url object.get_source_code_url end field :get_role, GraphQL::Types::String, null: true def get_role object.get_role end field :identifier, GraphQL::Types::String, null: true field :login, GraphQL::Types::String, null: true field :dbid, GraphQL::Types::Int, null: true field :installed, GraphQL::Types::Boolean, null: true field :installations_count, GraphQL::Types::Int, null: true field :settings_ui_schema, GraphQL::Types::String, null: true field :installation, TeamBotInstallationType, null: true field :default, GraphQL::Types::Boolean, null: true field :settings_as_json_schema, GraphQL::Types::String, null: true do argument :team_slug, GraphQL::Types::String, required: false, camelize: false # Some settings options are team-specific end def settings_as_json_schema(team_slug: nil) object.settings_as_json_schema(false, team_slug) end field :team_author, TeamType, null: true def team_author RecordLoader.for(Team).load(object.team_author_id.to_i) end end
class Front::PagesController < Front::BaseController def show raise ActionController::RoutingError, "Not Found" if params[:id].nil? render "front/pages/#{show_params[:id]}" end private def show_params params.permit(:id) end end
class RoomsController < ApplicationController before_action :set_room, only: [:show, :edit, :update, :destroy] # GET /rooms # GET /rooms.json def index @rooms = Room.all end def play @current_player = Player.where(id: params[:player_id], room_id: params[:room_id]).first @room = Room.find(params[:room_id]) @players = Player.where(room_id: @room.id) end def start_game @room = Room.find(params[:room_id]) @room.status = "ask_for_questions" @room.save end def check_status room = Room.find(params[:room_id]) # respond_to do |format| # format.text { room.status } # end render text: room.status end # GET /rooms/1 # GET /rooms/1.json def show end # GET /rooms/new def new @room = Room.new end # GET /rooms/1/edit def edit end # POST /rooms # POST /rooms.json def create @room = Room.new(room_params) @room.active = true @room.code = Room.unique_code respond_to do |format| if @room.save format.html { redirect_to @room, notice: 'Room was successfully created.' } format.json { render :show, status: :created, location: @room } else format.html { render :new } format.json { render json: @room.errors, status: :unprocessable_entity } end end end # PATCH/PUT /rooms/1 # PATCH/PUT /rooms/1.json def update respond_to do |format| if @room.update(room_params) format.html { redirect_to @room, notice: 'Room was successfully updated.' } format.json { render :show, status: :ok, location: @room } else format.html { render :edit } format.json { render json: @room.errors, status: :unprocessable_entity } end end end # DELETE /rooms/1 # DELETE /rooms/1.json def destroy @room.destroy respond_to do |format| format.html { redirect_to rooms_url, notice: 'Room was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_room @room = Room.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def room_params params.require(:room).permit(:name, :host) end end
class Ticket < ApplicationRecord belongs_to :user belongs_to :flat has_many :replies end
require 'spec_helper' describe PagesController do let(:valid_attributes){ {name: "home"}} describe "GET 'new'" do it "should assign a new page as @page" do get 'new' expect(assigns(:page)).to be_a_new(Page) end end describe "POST 'create'" do it "should create a page" do expect{ post 'create', {page: valid_attributes} }.to change(Page, :count).by(1) response.should redirect_to(pages_url) end it "should redirect to pages_url when successful" do post 'create', {page: valid_attributes} response.should redirect_to(pages_url) end end end
class User < ApplicationRecord has_many :user_videos has_many :videos, through: :user_videos has_many :friended_users, foreign_key: :friender_id, class_name: 'FriendUser' has_many :friendees, through: :friended_users has_many :friending_users, foreign_key: :friendee_id, class_name: 'FriendUser' has_many :frienders, through: :friending_users validates :email, uniqueness: true, presence: true validates_presence_of :password_digest validates_presence_of :first_name enum role: %w[default admin] has_secure_password def find_friends frienders end end
#GET request get '/sample-11-how-programmatically-create-and-post-an-annotation-into-document' do haml :sample11 end #POST request post '/sample-11-how-programmatically-create-and-post-an-annotation-into-document' do #Set variables set :client_id, params[:clientId] set :private_key, params[:privateKey] set :file_id, params[:fileId] set :annotation_type, params[:annotationType] set :annotation_id, params[:annotationId] set :base_path, params[:basePath] begin #Check required variables raise 'Please enter all required parameters' if settings.client_id.empty? or settings.private_key.empty? or settings.file_id.empty? or settings.annotation_type.empty? #Prepare base path if settings.base_path.empty? base_path = 'https://api.groupdocs.com' elsif settings.base_path.match('/v2.0') base_path = settings.base_path.split('/v2.0')[0] else base_path = settings.base_path end #Configure your access to API server GroupDocs.configure do |groupdocs| groupdocs.client_id = settings.client_id groupdocs.private_key = settings.private_key #Optionally specify API server and version groupdocs.api_server = base_path # default is 'https://api.groupdocs.com' end if settings.annotation_id != '' file = GroupDocs::Storage::File.new({:guid => settings.file_id}).to_document annotation = file.annotations!() #Remove annotation from document remove = annotation.last.remove!() message = "You delete the annotation id = #{remove[:guid]} " else #Annotation types types = {:text => "0", :area => "1", :point => "2"} #Required parameters all_params = all_params = ['annotationType', 'boxX', 'boxY', 'text'] #Added required parameters depends on annotation type ['text' or 'area'] if settings.annotation_type == 'text' all_params = all_params | ['boxWidth', 'boxHeight', 'annotationPositionX', 'annotationPositionY', 'rangePosition', 'rangeLength'] elsif settings.annotation_type == 'area' all_params = all_params | ['boxWidth', 'boxHeight'] end #raise all_params.to_yaml #Checking required parameters all_params.each do |param| raise 'Please enter all required parameters' if params[param].empty? end #Create document object document = GroupDocs::Storage::File.new(guid: settings.file_id).to_document unless document.instance_of? String #Start create new annotation annotation = GroupDocs::Document::Annotation.new(document: document) info = nil #Construct requestBody depends on annotation type #Text annotation if settings.annotation_type == 'text' annotation_box = {x: params['boxX'], y: params['boxY'], width: params['boxWidth'], height: params['boxHeight']} annotation_position = {x: params['annotationPositionX'], y: params['annotationPositionY']} range = {position: params['rangePosition'], length: params['rangeLength']} info = { :box => annotation_box, :annotationPosition => annotation_position, :range => range, :type => types[settings.annotation_type.to_sym], :replies => [{:text => params['text']}]} #Area annotation elsif settings.annotation_type == 'area' annotation_box = {x: params['boxX'], y: params['boxY'], width: params['boxWidth'], height: params['boxHeight']} annotation_annotationPosition = {x: 0, y: 0} info = {:box => annotation_box, :annotationPosition => annotation_annotationPosition, :type => types[settings.annotation_type.to_sym], :replies => [{:text => params['text']}]} #Point annotation elsif settings.annotation_type == 'point' annotation_box = {x: params['boxX'], y: params['boxY'], width: 0, height: 0} annotation_annotationPosition = {x: 0, y: 0} info = {:box => annotation_box, :annotationPosition => annotation_annotationPosition, :type => types[settings.annotation_type.to_sym], :replies => [{:text => params['text']}] } end #Call create method annotation.create!(info) id = annotation.document.file.id #Get document guid guid = annotation.document.file.guid #Prepare to sign url iframe = "/document-annotation2/embed/#{guid}" #Construct result string url = GroupDocs::Api::Request.new(:path => iframe).prepare_and_sign_url #Generate iframe URL case base_path when 'https://stage-api-groupdocs.dynabic.com' iframe = "https://stage-api-groupdocs.dynabic.com#{url}" when 'https://dev-api-groupdocs.dynabic.com' iframe = "https://dev-apps.groupdocs.com#{url}" else iframe = "https://apps.groupdocs.com#{url}" end #Make iframe iframe = "<iframe id='downloadframe' src='#{iframe}' width='800' height='1000'></iframe>" end end rescue Exception => e err = e.message end # set variables for template haml :sample11, :locals => {:clientId => settings.client_id, :privateKey => settings.private_key, :fileId => settings.file_id, :annotationType => settings.annotation_type, :annotationId => id, :annotationText => params['text'], :err => err, :iframe => iframe, :message => message} end
FactoryBot.define do factory :passport_authentication do otp { rand(100_000..999_999).to_s } otp_expires_at { 3.minutes.from_now } access_token { SecureRandom.hex(32) } patient_business_identifier do create(:patient_business_identifier, identifier_type: "simple_bp_passport") end end end
class User < ActiveRecord::Base has_secure_password has_many :cards has_many :scores has_many :decks has_many :favourites end
class CreateRealtors < ActiveRecord::Migration def change create_table :realtors do |t| t.string :name t.integer :hire_able_id t.string :hire_able_type t.timestamps end end end
Rails.application.routes.draw do # resources :tasks # resources :statuses namespace :admin do resources :tasks resources :statuses end root :to => 'admin/tasks#index' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module ServerSelector class Base # Initialize the server selector. # # @example Initialize the selector. # Mongo::ServerSelector::Secondary.new(:tag_sets => [{'dc' => 'nyc'}]) # # @example Initialize the preference with no options. # Mongo::ServerSelector::Secondary.new # # @param [ Hash ] options The server preference options. # # @option options [ Integer ] :local_threshold The local threshold boundary for # nearest selection in seconds. # @option options [ Integer ] max_staleness The maximum replication lag, # in seconds, that a secondary can suffer and still be eligible for a read. # A value of -1 is treated identically to nil, which is to not # have a maximum staleness. # @option options [ Hash | nil ] hedge A Hash specifying whether to enable hedged # reads on the server. Hedged reads are not enabled by default. When # specifying this option, it must be in the format: { enabled: true }, # where the value of the :enabled key is a boolean value. # # @raise [ Error::InvalidServerPreference ] If tag sets are specified # but not allowed. # # @api private def initialize(options = nil) options = options ? options.dup : {} if options[:max_staleness] == -1 options.delete(:max_staleness) end @options = options @tag_sets = options[:tag_sets] || [] @max_staleness = options[:max_staleness] @hedge = options[:hedge] validate! end # @return [ Hash ] options The options. attr_reader :options # @return [ Array ] tag_sets The tag sets used to select servers. attr_reader :tag_sets # @return [ Integer ] max_staleness The maximum replication lag, in # seconds, that a secondary can suffer and still be eligible for a read. # # @since 2.4.0 attr_reader :max_staleness # @return [ Hash | nil ] hedge The document specifying whether to enable # hedged reads. attr_reader :hedge # Get the timeout for server selection. # # @example Get the server selection timeout, in seconds. # selector.server_selection_timeout # # @return [ Float ] The timeout. # # @since 2.0.0 # # @deprecated This setting is now taken from the cluster options when # a server is selected. Will be removed in version 3.0. def server_selection_timeout @server_selection_timeout ||= (options[:server_selection_timeout] || ServerSelector::SERVER_SELECTION_TIMEOUT) end # Get the local threshold boundary for nearest selection in seconds. # # @example Get the local threshold. # selector.local_threshold # # @return [ Float ] The local threshold. # # @since 2.0.0 # # @deprecated This setting is now taken from the cluster options when # a server is selected. Will be removed in version 3.0. def local_threshold @local_threshold ||= (options[:local_threshold] || ServerSelector::LOCAL_THRESHOLD) end # @api private def local_threshold_with_cluster(cluster) options[:local_threshold] || cluster.options[:local_threshold] || LOCAL_THRESHOLD end # Inspect the server selector. # # @example Inspect the server selector. # selector.inspect # # @return [ String ] The inspection. # # @since 2.2.0 def inspect "#<#{self.class.name}:0x#{object_id} tag_sets=#{tag_sets.inspect} max_staleness=#{max_staleness.inspect} hedge=#{hedge}>" end # Check equality of two server selectors. # # @example Check server selector equality. # preference == other # # @param [ Object ] other The other preference. # # @return [ true, false ] Whether the objects are equal. # # @since 2.0.0 def ==(other) name == other.name && hedge == other.hedge && max_staleness == other.max_staleness && tag_sets == other.tag_sets end # Select a server from the specified cluster, taking into account # mongos pinning for the specified session. # # If the session is given and has a pinned server, this server is the # only server considered for selection. If the server is of type mongos, # it is returned immediately; otherwise monitoring checks on this # server are initiated to update its status, and if the server becomes # a mongos within the server selection timeout, it is returned. # # If no session is given or the session does not have a pinned server, # normal server selection process is performed among all servers in the # specified cluster matching the preference of this server selector # object. Monitoring checks are initiated on servers in the cluster until # a suitable server is found, up to the server selection timeout. # # If a suitable server is not found within the server selection timeout, # this method raises Error::NoServerAvailable. # # @param [ Mongo::Cluster ] cluster The cluster from which to select # an eligible server. # @param [ true, false ] ping Whether to ping the server before selection. # Deprecated and ignored. # @param [ Session | nil ] session Optional session to take into account # for mongos pinning. Added in version 2.10.0. # @param [ true | false ] write_aggregation Whether we need a server that # supports writing aggregations (e.g. with $merge/$out) on secondaries. # @param [ Array<Server> ] deprioritized A list of servers that should # be selected from only if no other servers are available. This is # used to avoid selecting the same server twice in a row when # retrying a command. # # @return [ Mongo::Server ] A server matching the server preference. # # @raise [ Error::NoServerAvailable ] No server was found matching the # specified preference / pinning requirement in the server selection # timeout. # @raise [ Error::LintError ] An unexpected condition was detected, and # lint mode is enabled. # # @since 2.0.0 def select_server(cluster, ping = nil, session = nil, write_aggregation: false, deprioritized: []) select_server_impl(cluster, ping, session, write_aggregation, deprioritized).tap do |server| if Lint.enabled? && !server.pool.ready? raise Error::LintError, 'Server selector returning a server with a pool which is not ready' end end end # Parameters and return values are the same as for select_server. private def select_server_impl(cluster, ping, session, write_aggregation, deprioritized) if cluster.topology.is_a?(Cluster::Topology::LoadBalanced) return cluster.servers.first end server_selection_timeout = cluster.options[:server_selection_timeout] || SERVER_SELECTION_TIMEOUT # Special handling for zero timeout: if we have to select a server, # and the timeout is zero, fail immediately (since server selection # will take some non-zero amount of time in any case). if server_selection_timeout == 0 msg = "Failing server selection due to zero timeout. " + " Requested #{name} in cluster: #{cluster.summary}" raise Error::NoServerAvailable.new(self, cluster, msg) end deadline = Utils.monotonic_time + server_selection_timeout if session && session.pinned_server if Mongo::Lint.enabled? unless cluster.sharded? raise Error::LintError, "Session has a pinned server in a non-sharded topology: #{topology}" end end if !session.in_transaction? session.unpin end if server = session.pinned_server # Here we assume that a mongos stays in the topology indefinitely. # This will no longer be the case once SRV polling is implemented. unless server.mongos? while (time_remaining = deadline - Utils.monotonic_time) > 0 wait_for_server_selection(cluster, time_remaining) end unless server.mongos? msg = "The session being used is pinned to the server which is not a mongos: #{server.summary} " + "(after #{server_selection_timeout} seconds)" raise Error::NoServerAvailable.new(self, cluster, msg) end end return server end end if cluster.replica_set? validate_max_staleness_value_early! end if cluster.addresses.empty? if Lint.enabled? unless cluster.servers.empty? raise Error::LintError, "Cluster has no addresses but has servers: #{cluster.servers.map(&:inspect).join(', ')}" end end msg = "Cluster has no addresses, and therefore will never have a server" raise Error::NoServerAvailable.new(self, cluster, msg) end =begin Add this check in version 3.0.0 unless cluster.connected? msg = 'Cluster is disconnected' raise Error::NoServerAvailable.new(self, cluster, msg) end =end loop do if Lint.enabled? cluster.servers.each do |server| # TODO: Add this back in RUBY-3174. # if !server.unknown? && !server.connected? # raise Error::LintError, "Server #{server.summary} is known but is not connected" # end if !server.unknown? && !server.pool.ready? raise Error::LintError, "Server #{server.summary} is known but has non-ready pool" end end end server = try_select_server(cluster, write_aggregation: write_aggregation, deprioritized: deprioritized) if server unless cluster.topology.compatible? raise Error::UnsupportedFeatures, cluster.topology.compatibility_error.to_s end if session && session.starting_transaction? && cluster.sharded? session.pin_to_server(server) end return server end cluster.scan!(false) time_remaining = deadline - Utils.monotonic_time if time_remaining > 0 wait_for_server_selection(cluster, time_remaining) # If we wait for server selection, perform another round of # attempting to locate a suitable server. Otherwise server selection # can raise NoServerAvailable message when the diagnostics # reports an available server of the requested type. else break end end msg = "No #{name} server" if is_a?(ServerSelector::Secondary) && !tag_sets.empty? msg += " with tag sets: #{tag_sets}" end msg += " is available in cluster: #{cluster.summary} " + "with timeout=#{server_selection_timeout}, " + "LT=#{local_threshold_with_cluster(cluster)}" msg += server_selection_diagnostic_message(cluster) raise Error::NoServerAvailable.new(self, cluster, msg) rescue Error::NoServerAvailable => e if session && session.in_transaction? && !session.committing_transaction? e.add_label('TransientTransactionError') end if session && session.committing_transaction? e.add_label('UnknownTransactionCommitResult') end raise e end # Tries to find a suitable server, returns the server if one is available # or nil if there isn't a suitable server. # # @param [ Mongo::Cluster ] cluster The cluster from which to select # an eligible server. # @param [ true | false ] write_aggregation Whether we need a server that # supports writing aggregations (e.g. with $merge/$out) on secondaries. # @param [ Array<Server> ] deprioritized A list of servers that should # be selected from only if no other servers are available. This is # used to avoid selecting the same server twice in a row when # retrying a command. # # @return [ Server | nil ] A suitable server, if one exists. # # @api private def try_select_server(cluster, write_aggregation: false, deprioritized: []) servers = if write_aggregation && cluster.replica_set? # 1. Check if ALL servers in cluster support secondary writes. is_write_supported = cluster.servers.reduce(true) do |res, server| res && server.features.merge_out_on_secondary_enabled? end if is_write_supported # 2. If all servers support secondary writes, we respect read preference. suitable_servers(cluster) else # 3. Otherwise we fallback to primary for replica set. [cluster.servers.detect(&:primary?)] end else suitable_servers(cluster) end # This list of servers may be ordered in a specific way # by the selector (e.g. for secondary preferred, the first # server may be a secondary and the second server may be primary) # and we should take the first server here respecting the order server = suitable_server(servers, deprioritized) if server if Lint.enabled? # It is possible for a server to have a nil average RTT here # because the ARTT comes from description which may be updated # by a background thread while server selection is running. # Currently lint mode is not a public feature, if/when this # changes (https://jira.mongodb.org/browse/RUBY-1576) the # requirement for ARTT to be not nil would need to be removed. if server.average_round_trip_time.nil? raise Error::LintError, "Server #{server.address} has nil average rtt" end end end server end # Returns servers of acceptable types from the cluster. # # Does not perform staleness validation, staleness filtering or # latency filtering. # # @param [ Cluster ] cluster The cluster. # # @return [ Array<Server> ] The candidate servers. # # @api private def candidates(cluster) servers = cluster.servers servers.each do |server| validate_max_staleness_support!(server) end if cluster.single? servers elsif cluster.sharded? servers elsif cluster.replica_set? select_in_replica_set(servers) else # Unknown cluster - no servers [] end end # Returns servers satisfying the server selector from the cluster. # # @param [ Cluster ] cluster The cluster. # # @return [ Array<Server> ] The suitable servers. # # @api private def suitable_servers(cluster) if cluster.single? candidates(cluster) elsif cluster.sharded? local_threshold = local_threshold_with_cluster(cluster) servers = candidates(cluster) near_servers(servers, local_threshold) elsif cluster.replica_set? validate_max_staleness_value!(cluster) candidates(cluster) else # Unknown cluster - no servers [] end end private # Returns a server from the list of servers that is suitable for # executing the operation. # # @param [ Array<Server> ] servers The candidate servers. # @param [ Array<Server> ] deprioritized A list of servers that should # be selected from only if no other servers are available. # # @return [ Server | nil ] The suitable server or nil if no suitable # server is available. def suitable_server(servers, deprioritized) preferred = servers - deprioritized if preferred.empty? servers.first else preferred.first end end # Convert this server preference definition into a format appropriate # for sending to a MongoDB server (i.e., as a command field). # # @return [ Hash ] The server preference formatted as a command field value. # # @since 2.0.0 def full_doc @full_doc ||= begin preference = { :mode => self.class.const_get(:SERVER_FORMATTED_NAME) } preference.update(tags: tag_sets) unless tag_sets.empty? preference.update(maxStalenessSeconds: max_staleness) if max_staleness preference.update(hedge: hedge) if hedge preference end end # Select the primary from a list of provided candidates. # # @param [ Array ] candidates List of candidate servers to select the # primary from. # # @return [ Array ] The primary. # # @since 2.0.0 def primary(candidates) candidates.select do |server| server.primary? end end # Select the secondaries from a list of provided candidates. # # @param [ Array ] candidates List of candidate servers to select the # secondaries from. # # @return [ Array ] The secondary servers. # # @since 2.0.0 def secondaries(candidates) matching_servers = candidates.select(&:secondary?) matching_servers = filter_stale_servers(matching_servers, primary(candidates).first) matching_servers = match_tag_sets(matching_servers) unless tag_sets.empty? # Per server selection spec the server selected MUST be a random # one matching staleness and latency requirements. # Selectors always pass the output of #secondaries to #nearest # which shuffles the server list, fulfilling this requirement. matching_servers end # Select the near servers from a list of provided candidates, taking the # local threshold into account. # # @param [ Array ] candidates List of candidate servers to select the # near servers from. # @param [ Integer ] local_threshold Local threshold. This parameter # will be required in driver version 3.0. # # @return [ Array ] The near servers. # # @since 2.0.0 def near_servers(candidates = [], local_threshold = nil) return candidates if candidates.empty? # Average RTT on any server may change at any time by the server # monitor's background thread. ARTT may also become nil if the # server is marked unknown. Take a snapshot of ARTTs for the duration # of this method. candidates = candidates.map do |server| {server: server, artt: server.average_round_trip_time} end.reject do |candidate| candidate[:artt].nil? end return candidates if candidates.empty? nearest_candidate = candidates.min_by do |candidate| candidate[:artt] end # Default for legacy signarure local_threshold ||= self.local_threshold threshold = nearest_candidate[:artt] + local_threshold candidates.select do |candidate| candidate[:artt] <= threshold end.map do |candidate| candidate[:server] end.shuffle! end # Select the servers matching the defined tag sets. # # @param [ Array ] candidates List of candidate servers from which those # matching the defined tag sets should be selected. # # @return [ Array ] The servers matching the defined tag sets. # # @since 2.0.0 def match_tag_sets(candidates) matches = [] tag_sets.find do |tag_set| matches = candidates.select { |server| server.matches_tag_set?(tag_set) } !matches.empty? end matches || [] end def filter_stale_servers(candidates, primary = nil) return candidates unless @max_staleness # last_scan is filled out by the Monitor, and can be nil if a server # had its description manually set rather than being normally updated # via the SDAM flow. We don't handle the possibility of a nil # last_scan here. if primary candidates.select do |server| validate_max_staleness_support!(server) staleness = (server.last_scan - server.last_write_date) - (primary.last_scan - primary.last_write_date) + server.cluster.heartbeat_interval staleness <= @max_staleness end else max_write_date = candidates.collect(&:last_write_date).max candidates.select do |server| validate_max_staleness_support!(server) staleness = max_write_date - server.last_write_date + server.cluster.heartbeat_interval staleness <= @max_staleness end end end def validate! if !@tag_sets.all? { |set| set.empty? } && !tags_allowed? raise Error::InvalidServerPreference.new(Error::InvalidServerPreference::NO_TAG_SUPPORT) elsif @max_staleness && !max_staleness_allowed? raise Error::InvalidServerPreference.new(Error::InvalidServerPreference::NO_MAX_STALENESS_SUPPORT) end if @hedge unless hedge_allowed? raise Error::InvalidServerPreference.new(Error::InvalidServerPreference::NO_HEDGE_SUPPORT) end unless @hedge.is_a?(Hash) && @hedge.key?(:enabled) && [true, false].include?(@hedge[:enabled]) raise Error::InvalidServerPreference.new( "`hedge` value (#{hedge}) is invalid - hedge must be a Hash in the " \ "format { enabled: true }" ) end end end def validate_max_staleness_support!(server) if @max_staleness && !server.features.max_staleness_enabled? raise Error::InvalidServerPreference.new(Error::InvalidServerPreference::NO_MAX_STALENESS_WITH_LEGACY_SERVER) end end def validate_max_staleness_value_early! if @max_staleness unless @max_staleness >= SMALLEST_MAX_STALENESS_SECONDS msg = "`max_staleness` value (#{@max_staleness}) is too small - it must be at least " + "`Mongo::ServerSelector::SMALLEST_MAX_STALENESS_SECONDS` (#{ServerSelector::SMALLEST_MAX_STALENESS_SECONDS})" raise Error::InvalidServerPreference.new(msg) end end end def validate_max_staleness_value!(cluster) if @max_staleness heartbeat_interval = cluster.heartbeat_interval unless @max_staleness >= [ SMALLEST_MAX_STALENESS_SECONDS, min_cluster_staleness = heartbeat_interval + Cluster::IDLE_WRITE_PERIOD_SECONDS, ].max msg = "`max_staleness` value (#{@max_staleness}) is too small - it must be at least " + "`Mongo::ServerSelector::SMALLEST_MAX_STALENESS_SECONDS` (#{ServerSelector::SMALLEST_MAX_STALENESS_SECONDS}) and (the cluster's heartbeat_frequency " + "setting + `Mongo::Cluster::IDLE_WRITE_PERIOD_SECONDS`) (#{min_cluster_staleness})" raise Error::InvalidServerPreference.new(msg) end end end # Waits for server state changes in the specified cluster. # # If the cluster has a server selection semaphore, waits on that # semaphore up to the specified remaining time. Any change in server # state resulting from SDAM will immediately wake up this method and # cause it to return. # # If the cluster des not have a server selection semaphore, waits # the smaller of 0.25 seconds and the specified remaining time. # This functionality is provided for backwards compatibilty only for # applications directly invoking the server selection process. # If lint mode is enabled and the cluster does not have a server # selection semaphore, Error::LintError will be raised. # # @param [ Cluster ] cluster The cluster to wait for. # @param [ Numeric ] time_remaining Maximum time to wait, in seconds. def wait_for_server_selection(cluster, time_remaining) if cluster.server_selection_semaphore # Since the semaphore may have been signaled between us checking # the servers list earlier and the wait call below, we should not # wait for the full remaining time - wait for up to 0.5 second, then # recheck the state. cluster.server_selection_semaphore.wait([time_remaining, 0.5].min) else if Lint.enabled? raise Error::LintError, 'Waiting for server selection without having a server selection semaphore' end sleep [time_remaining, 0.25].min end end # Creates a diagnostic message when server selection fails. # # The diagnostic message includes the following information, as applicable: # # - Servers having dead monitor threads # - Cluster is disconnected # # If none of the conditions for diagnostic messages apply, an empty string # is returned. # # @param [ Cluster ] cluster The cluster on which server selection was # performed. # # @return [ String ] The diagnostic message. def server_selection_diagnostic_message(cluster) msg = '' dead_monitors = [] cluster.servers_list.each do |server| thread = server.monitor.instance_variable_get('@thread') if thread.nil? || !thread.alive? dead_monitors << server end end if dead_monitors.any? msg += ". The following servers have dead monitor threads: #{dead_monitors.map(&:summary).join(', ')}" end unless cluster.connected? msg += ". The cluster is disconnected (client may have been closed)" end msg end end end end
class AddNewColumnToPhotos < ActiveRecord::Migration def change add_column :photos, :file_data, :string end end
require 'test_helper' class MyNetworkControllerTest < ActionController::TestCase include Devise::TestHelpers test "should not get show page if user isnt signed in" do get 'show' assert_response :redirect assert_redirected_to '/users/sign_in' end test "should get show page if user signed in" do sign_in users(:me) get 'show' assert_response :success assert_template 'show' assert_template layout: 'layouts/application' end end
# frozen_string_literal: true require 'globalize/automatic/translator' require 'easy_translate' class Globalize::Automatic::Translator::EasyTranslate < Globalize::Automatic::Translator def translate(text, from, to) ::EasyTranslate.translate(text, from: from, to: to) end end
class PostsController < ApplicationController # http_basic_authenticate_with name: "username",password: "password", except: [:index, :show] def index @posts = Post.all end def show @user = User.find(params[:user_id]) @blog = Blog.find(params[:blog_id]) @post = @blog.posts.find(params[:id]) end def new @post = Post.new end def edit @user = User.find(params[:user_id]) @blog = Blog.find(params[:blog_id]) @post = @blog.posts.find(params[:id]) end def create @user = User.find(params[:user_id]) @blog = Blog.find(params[:blog_id]) # @post = Post.new(post_params) @post = @blog.posts.create(post_params) if @post.save # redirect_to @post redirect_to user_blog_post_path(@user, @blog, @post) else render 'new' end end def update @user = User.find(params[:user_id]) @blog = Blog.find(params[:blog_id]) @post = @blog.posts.find(params[:id]) # if the update method fails b/c of validations then it returns false and doesn't update if @post.update(post_params) redirect_to user_blog_post_path(@user, @blog, @post) else render 'edit' end end def destroy @user = User.find(params[:user_id]) @blog = Blog.find(params[:blog_id]) @post = @blog.posts.find(params[:id]) @post.destroy redirect_to user_blog_path(@user, @blog) end private def post_params params.require(:post).permit(:title, :body) end end
class Form::Product < Product REGISTRABLE_ATTRIBUTES = %i(register name price tax_price division product_category_id) attr_accessor :register end
# == Schema Information # # Table name: room_contacts # # id :bigint not null, primary key # room_id :bigint # rmrecnbr :integer # rm_schd_cntct_name :string # rm_schd_email :string # rm_schd_cntct_phone :string # rm_det_url :string # rm_usage_guidlns_url :string # rm_sppt_deptid :string # rm_sppt_dept_descr :string # rm_sppt_cntct_email :string # rm_sppt_cntct_phone :string # rm_sppt_cntct_url :string # require "rails_helper" RSpec.describe RoomContact, type: :model do let(:room_contact) { build(:room_contact) } describe RoomContact do describe "Valid RoomContacts" do it { should validate_presence_of(:rmrecnbr) } end end end
class ListingsController < ApplicationController before_action :authenticate_user!, only: %i[new edit list] before_action :set_listing, only: %i[show] before_action :authorize_listing, only: %i[edit update destroy] def list @my_listings = current_user.listings end #-------------------------------------- # Queries the postcode column of the addresses model of the current user # Queries the postcode column of the addresses model for all users via the User model # Queries the listing model for sellers (FK) which belong to the addresses model #-------------------------------------- def index if user_signed_in? @listings = [] current_user.addresses.includes(user: { addresses: [] }).pluck(:postcode).uniq.each do |cupc| Listing.with_attached_images.all.active.includes(user: { addresses: [] }).each do |listing| pc = listing.user.addresses.first.postcode @listings << listing if pc == cupc end end @listings else @listings = Listing.with_attached_images.all.active.sample(6) end end def new @listing = Listing.new end #-------------------------------------- # Queries the Listings Model adds to the model with a column user_id as forgien key #-------------------------------------- def create @listing = current_user.listings.new(listing_params) # @listing.status = 1 if @listing.save redirect_to @listing else render :new end end def edit; end #-------------------------------------- # Queries the Listings Model and changes coloumns specified by the user #-------------------------------------- def update if @listing.update(listing_params) redirect_to @listing else render :edit end end #-------------------------------------- # Queries Listing model, checks if listing belongs to current user #-------------------------------------- def show if user_signed_in? stripe_session = Stripe::Checkout::Session.create( payment_method_types: ["card"], client_reference_id: current_user ? current_user.id : nil, customer_email: current_user ? current_user.email : nil, line_items: [{ amount: (@listing.price * 100).to_i, name: @listing.name, description: @listing.description, currency: "aud", quantity: 1, }], payment_intent_data: { metadata: { listing_id: @listing.id, user_id: current_user ? current_user.id : nil, }, }, success_url: "#{root_url}purchases/success?listingId=#{@listing.id}", cancel_url: "#{root_url}listings", ) @session_id = stripe_session.id else flash[:alert] = "Sign up to purchase today!" end end #-------------------------------------- # Queries the Listing Model and removes from model via the pk column #-------------------------------------- def destroy @listing.destroy flash[:alert] = "Deleted Listing" redirect_to listings_path end private def listing_params params.require(:listing).permit(:name, :description, :price, :category, :images) end def authorize_listing @listing = current_user.listings.find_by_id(params[:id]) return if @listing flash[:alert] = "You do not have permissions to access this page" redirect_to listings_path end def set_listing @listing = Listing.with_attached_images.find(params[:id]) end end
require_relative '../test_helper' # Testing the real config class OpenTelemetryConfigTest < ActiveSupport::TestCase ENV_CONFIG_TO_RESET = %w( OTEL_TRACES_EXPORTER OTEL_EXPORTER_OTLP_ENDPOINT OTEL_EXPORTER_OTLP_HEADERS OTEL_RESOURCE_ATTRIBUTES OTEL_TRACES_SAMPLER OTEL_TRACES_SAMPLER_ARG ) def cache_and_clear_env {}.tap do |original_state| ENV_CONFIG_TO_RESET.each do|env_var| next unless ENV[env_var] original_state[env_var] = ENV.delete(env_var) end end end test "configures open telemetry to report remotely when exporting enabled" do env_var_original_state = cache_and_clear_env Check::OpenTelemetryConfig.new('https://fake.com','foo=bar').configure!({'developer.name' => 'piglet'}) assert_equal 'otlp', ENV['OTEL_TRACES_EXPORTER'] assert_equal 'https://fake.com', ENV['OTEL_EXPORTER_OTLP_ENDPOINT'] assert_equal 'foo=bar', ENV['OTEL_EXPORTER_OTLP_HEADERS'] assert_equal 'developer.name=piglet', ENV['OTEL_RESOURCE_ATTRIBUTES'] ensure env_var_original_state.each{|env_var, original_state| ENV[env_var] = original_state} end test "configures open telemetry to have nil exporter when exporting disabled, and leaves other exporter settings blank" do env_var_original_state = cache_and_clear_env Check::OpenTelemetryConfig.new('','').configure!({'developer.name' => 'piglet'}) assert_equal 'none', ENV['OTEL_TRACES_EXPORTER'] assert_nil ENV['OTEL_EXPORTER_OTLP_ENDPOINT'] assert_nil ENV['OTEL_EXPORTER_OTLP_HEADERS'] assert_equal 'developer.name=piglet', ENV['OTEL_RESOURCE_ATTRIBUTES'] ensure env_var_original_state.each{|env_var, original_state| ENV[env_var] = original_state} end test "sets provided sampling config in the environment" do env_var_original_state = cache_and_clear_env Check::OpenTelemetryConfig.new('https://fake.com','foo=bar').configure!( {'developer.name' => 'piglet' }, sampling_config: { sampler: 'traceidratio', rate: '2' } ) assert_equal 'traceidratio', ENV['OTEL_TRACES_SAMPLER'] assert_equal '0.5', ENV['OTEL_TRACES_SAMPLER_ARG'] assert_equal 'developer.name=piglet,SampleRate=2', ENV['OTEL_RESOURCE_ATTRIBUTES'] ensure env_var_original_state.each{|env_var, original_state| ENV[env_var] = original_state} end test "does not set the sampler arguments when sampling config cannot be set properly" do env_var_original_state = cache_and_clear_env Check::OpenTelemetryConfig.new('https://fake.com','foo=bar').configure!( {'developer.name' => 'piglet' }, sampling_config: { sampler: 'traceidratio', rate: 'asdf' } ) assert_nil ENV['OTEL_TRACES_SAMPLER_ARG'] assert_equal 'developer.name=piglet', ENV['OTEL_RESOURCE_ATTRIBUTES'] # Keeps sampler, since it could be something like alwayson or alwaysoff, which does # not require a sample rate assert_equal 'traceidratio', ENV['OTEL_TRACES_SAMPLER'] ensure env_var_original_state.each{|env_var, original_state| ENV[env_var] = original_state} end test "gracefully handles unset attributes" do env_var_original_state = cache_and_clear_env Check::OpenTelemetryConfig.new('https://fake.com','foo=bar').configure!(nil) assert ENV['OTEL_RESOURCE_ATTRIBUTES'].blank? ensure env_var_original_state.each{|env_var, original_state| ENV[env_var] = original_state} end test "does not sample if sampling override given" do env_var_original_state = cache_and_clear_env Check::OpenTelemetryConfig.new( 'https://fake.com', 'foo=bar', disable_sampling: 'true' ).configure!( {'developer.name' => 'piglet' }, sampling_config: { sampler: 'traceidratio', rate: 'asdf' } ) assert_nil ENV['OTEL_TRACES_SAMPLER'] assert_nil ENV['OTEL_TRACES_SAMPLER_ARG'] assert_equal 'developer.name=piglet', ENV['OTEL_RESOURCE_ATTRIBUTES'] ensure env_var_original_state.each{|env_var, original_state| ENV[env_var] = original_state} end # .tracer test "returns a configured tracer" do env_var_original_state = cache_and_clear_env tracer = Check::OpenTelemetryConfig.tracer assert tracer.is_a?(OpenTelemetry::Trace::Tracer) ensure env_var_original_state.each{|env_var, original_state| ENV[env_var] = original_state} end # .exporting_disabled? test "should disable exporting if any required config missing" do assert Check::OpenTelemetryConfig.new(nil, nil).send(:exporting_disabled?) assert Check::OpenTelemetryConfig.new('https://fake.com', '').send(:exporting_disabled?) assert !Check::OpenTelemetryConfig.new('https://fake.com', 'foo=bar').send(:exporting_disabled?) end test "should disable exporting if override set" do assert Check::OpenTelemetryConfig.new('https://fake.com', 'foo=bar', disable_exporting: 'true').send(:exporting_disabled?) end # .format_attributes test "should format attributes from hash to string, if present" do assert !Check::OpenTelemetryConfig.new(nil,nil).send(:format_attributes, nil) attr_string = Check::OpenTelemetryConfig.new(nil,nil).send(:format_attributes, {'developer.name' => 'piglet', 'favorite.food' => 'ham'}) assert_equal "developer.name=piglet,favorite.food=ham", attr_string end end
json.array!(@drivers) do |driver| json.extract! driver, :id, :firstName, :lastName, :licenseid, :company json.url driver_url(driver, format: :json) end
#!/usr/bin/ruby # -*- coding: euc-jp -*- #テーマ:ISBNのチェックディジットを計算 #入力:ISBNコード,10桁 #出力:valid or invalid require 'rspec' ISBN_FORMAT_REGEXP = /\A\d{9}[\dX]\z/ def valid_isbn?(isbn) return false if isbn !~ ISBN_FORMAT_REGEXP sum = 0 weight = 10 (0..8).each {|index| sum += isbn[index, 1].to_i * weight weight -= 1 } expected_check_digit = 11 - sum % 11 actual_check_digit_character = isbn[9, 1] actual_check_digit = actual_check_digit_character == "X" ? 10 : actual_check_digit_character.to_i expected_check_digit == actual_check_digit end describe "ISBN validator" do it "should recognize 453578258X as valid" do valid_isbn?("453578258X").should be_true end it "should recognize 4797324295 as valid" do valid_isbn?("4797324295").should be_true end it "should recognize 4797324290 as invalid" do valid_isbn?("4797324290").should be_false end it "should recognize ISBN having not digit as invalid" do valid_isbn?("45357a258X").should be_false end it "should recognize Yasda as invalid" do valid_isbn?("Yasda").should be_false end it "should recognize 4797314087 as valid" do valid_isbn?("4797314087").should be_true end it "should recognize 4797314a87 as invalid" do valid_isbn?("4797314a87").should be_false end it "should recognize too short code as invalid" do valid_isbn?("479731408").should be_false end it "should recognize too long code as invalid" do valid_isbn?("479731408777").should be_false end it "should recognize ISBN ending with return code as invalid" do valid_isbn?("4797314087\n").should be_false end it "should recognize ISBN having space as invalid" do valid_isbn?("479731408 7").should be_false end end
# frozen_string_literal: true # This controller manage the {User} model for the admins class Admin::UsersController < Admin::ApplicationController before_action :set_user, only: %i[show edit update] # GET /admin/users def index; end # GET /admin/users/list.html # GET /admin/users/list.json def list @search = {} @search[:editor] = true if filter_params[:editor] == '1' @search[:admin] = true if filter_params[:admin] == '1' @text = ['username ilike :text', text: "%#{filter_params[:text]}%"] if filter_params[:text].present? @pagy, @users = pagy(User.where(@search).where(@text)) end # GET /admin/users/:id def show; end # GET /admin/users/:id/edit def edit @groups = Group.all.order(:title).pluck :title, :id end # PATCH/PUT /admin/users/:id def update if @user.update(user_params) redirect_to admin_user_path(@user), notice: 'User was successfully updated.' else render :edit end end private # set @user when needed def set_user @user = User.find(params[:id]) end # Filter params for set an {User} def user_params params.require(:user).permit(:editor, :admin, group_ids: []) end # Filter params for search an {User} def filter_params params.fetch(:filter, {}).permit(:text, :editor, :admin) end end
# frozen_string_literal: true require 'bibtex' require 'traject/macros/marc21' require 'traject/macros/marc21_semantics' require 'active_support/core_ext/module' # Allows us to delegate to Bibtex require_relative './helpers' AUTHOR_TAGS = %w[100 700].freeze PUBLICATION_TAGS = %w[260 264].freeze module FindIt module Macros # extend Traject::Macros::BibTeX # to_field "bibtex_t", generate_bibtex module Bibtex # macro that generates a basic bibtex entry for an item def generate_bibtex proc do |record, accumulator| accumulator << FindIt::Macros::BibtexGenerator.new(record).to_s end end end # Create a Bibtex bibliography entry for a given MARC record class BibtexGenerator include FindIt::Data delegate :to_s, to: :@entry def initialize(marc_record) @entry = BibTeX::Entry.new @record = marc_record add_metadata end private def add_metadata add_authors add_publication_info add_title add_type add_url end def add_authors authors = @record.find_all { |f| AUTHOR_TAGS.include? f.tag } .map { |f| f.find { |sf| sf.code == 'a' }&.value } @entry.author = authors.join(' and ') if authors end def add_publication_info pub_field = @record.find { |f| PUBLICATION_TAGS.include? f.tag } @entry.address = pub_field['a'] if pub_field && pub_field['a'] @entry.publisher = pub_field['b'] if pub_field && pub_field['b'] end def add_type @entry.type = online_resource?(@record) ? :misc : :book end def add_title @entry.title = ::Traject::Macros::Marc21.trim_punctuation @record['245']['a'] end def add_url url = @record.find { |f| f.tag == '856' } @entry.url = url['u'] if url end def add_year @entry.year = ::Traject::Macros::Marc21Semantics.publication_date(@record) end end end end
class Podcast include DataMapper::Resource property :id, Serial property :title, String, length: 500, required: true property :rssurl, URI, format: :url, unique: true, required: true property :url, URI, format: :url, required: true property :paused, Boolean, default: false has n, :episodes, constraint: :destroy before :valid?, :set_url before :valid?, :set_rssurl before :valid?, :set_title private def set_title(context = :default) begin # Remove key words from titles title.gsub!(/(uploads by|vimeo|feed|quicktime|podcast|in hd|mp3|ogg|mp4|screencast(s)?)/i, '') title.gsub!(/\([\w\s-]+\)/, '') # Remove (hd - 30fps) title.gsub!(/[']+/, '') # Remove single quotes title.gsub!(/\W+/, ' ') # Remove no word characters title.strip! title rescue => e puts e end end def self.rssurls all(:fields => [:rssurl]) end def set_url(context = :default) begin self.url = url.to_s.downcase rescue => e puts e end end def set_rssurl(context = :default) begin self.rssurl = rssurl.to_s.downcase rescue => e puts e end end end
class CreateEmailTemplatesStatesTable < ActiveRecord::Migration def up create_table :email_templates_states, :id => false do |t| t.references :email_template t.references :state end add_index :email_templates_states, [:email_template_id, :state_id] add_index :email_templates_states, [:state_id,:email_template_id] end def down drop_table :email_templates_states end end
class DonationService < Validators::CharityValidator attr_reader :charge def initialize(options = {}) @charity = set_charity(options[:charity]) @token = options[:omise_token] @amount = options[:amount] @errors = [] end def process if valid? process_charge process_credit_amount else @token = get_retrieve_token end end def formatted_amount Money.new(charge.amount, Charity::DEFAULT_CURRENCY).format end private def set_charity(charity) charity == 'random' ? Charity.random_charity : Charity.find_by(id: charity) end def get_retrieve_token Omise::Token.retrieve(token) if token.present? end def process_charge @charge = Omise::Charge.create({ amount: (amount.to_f * 100).round, currency: "THB", card: token, description: "Donation to #{charity.name} [#{charity.id}]", }) end def process_credit_amount charity.credit_amount(charge.amount) && return if charge.paid errors << I18n.t('website.donate.failure') @token = nil end end
class Usermongo include Mongoid::Document # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable ## Database authenticatable field :email, :type => String, :default => "" field :encrypted_password, :type => String, :default => "" field :current_sign_in_at, :type => String, :default => "" field :current_sign_in_ip, :type => String, :default => "" field :last_sign_in_ip, :type => String, :default => "" field :last_sign_in_at, :type => String, :default => "" field :sign_in_count, :type => Integer, :default => "" field :remember_created_at, :type => Integer, :default => "" end
require 'yt/collections/base' require 'yt/models/snippet' module Yt module Collections # @private class GroupInfos < Base private def attributes_for_new_item(data) {data: data, auth: @auth} end def list_params super.tap do |params| params[:path] = "/youtube/analytics/v1/groups" params[:params] = {id: @parent.id} if @auth.owner_name params[:params][:on_behalf_of_content_owner] = @auth.owner_name end end end end end end
require 'secure_container/password_v1' RSpec.describe SecureContainer::PasswordV1 do shared_examples 'valid passwords' do |passwords| describe 'valid passwords' do passwords.each do |password| it password do expect(described_class.new(password)).to be_valid end end end end shared_examples 'invalid passwords' do |passwords| describe 'invalid passwords' do passwords.each do |password| it password do expect(described_class.new(password)).to_not be_valid end end end end include_examples 'valid passwords', [ '111123', '111111' ] include_examples 'invalid passwords', [ '223450', '123789' ] end
require 'spec_helper' require_relative '../environment.rb' describe 'Environment' do let!(:new_environment) { Environment.new(5,10, 1) } let!(:happy_place) { Environment.new(5,10, 1) } let!(:place_of_death) { Environment.new(5,10, 0) } let!(:soso_place) { Environment.new(5,10, 0.5) } context "when initialized as 5x10" do it "is a Cell object" do expect(new_environment).to be_an(Environment) end it "has height and width properties" do expect(new_environment.height).to eq(5) expect(new_environment.width).to eq(10) end it "has a size of 25 (5x5)" do expect(new_environment.cells.flatten.length).to eq(50) end it "has an empty population (ie, no cells)" do new_environment.cells.flatten.each { |cell| expect(cell).to eq(nil) } end end context "in terms of culturing the entire environment" do context "after the full environment has been cultured" do it "contains 50 cells" do new_environment.culture_cells 50.times { |index| expect(new_environment.cells.flatten[index]).to be_a(Cell)} end end context "when entirely hospitable" do it "all of the cells cultured will initially be living" do happy_place.culture_cells 50.times { |index| expect(happy_place.cells.flatten[index].living).to eq(true)} end end context "when entirely inhospitable" do it "all of the cells cultured will initially be dead" do place_of_death.culture_cells 50.times { |index| expect(place_of_death.cells.flatten[index].dead).to eq(true)} end end context "when 50% inhospitable" do it "approximately half of the cells cultured will initially be living" do soso_place.culture_cells num_living_cells = 0 soso_place.height.times do |row| soso_place.width.times do |col| num_living_cells += 1 if soso_place.cells[row][col].living end end expect(15..35).to include(num_living_cells) end end end context "when cells are cultured in a specific location" do it "creates live cells in the specific location" do new_environment.culture_cell(0,0) new_environment.culture_cell(4,4,false) expect(new_environment.cells[0][0].living).to eq(true) expect(new_environment.cells[4][4].dead).to eq(true) end end context "when cells are cultured in a 4x4 environment" do # XX__ # XX__ # ____ # ____ it "num_living_neighbors property works" do e = Environment.new(4,4,0) e.culture_cells e.culture_cell(0,0) e.culture_cell(0,1) e.culture_cell(1,0) e.culture_cell(1,1) expect(e.num_living_neighbors(0,0)).to eq(3) expect(e.num_living_neighbors(0,1)).to eq(3) expect(e.num_living_neighbors(1,0)).to eq(3) expect(e.num_living_neighbors(1,1)).to eq(3) expect(e.num_living_neighbors(0,2)).to eq(2) expect(e.num_living_neighbors(1,2)).to eq(2) expect(e.num_living_neighbors(2,2)).to eq(1) expect(e.num_living_neighbors(3,3)).to eq(0) end end describe "neighbors" do context "when only one cell has been created in an environment" do let!(:environment_1x1) { Environment.new(1, 1, 1) } before(:each) do environment_1x1.culture_cells end it "responds to 'num_living_neighbors' method" do expect(environment_1x1.cells[0][0]).to respond_to(:num_living_neighbors) end it "has zero neighbors" do environment_1x1.set_num_living_neighbors_for_all_cells cell = environment_1x1.cells[0][0] expect(cell.num_living_neighbors).to eq(0) end end end context "Implementation of Rules" do let!(:new_environment) { Environment.new(5, 5, 0) } context "Rule 1: when living cells have only 0 or 1 neighbor" do it "the cells die after a tick" do new_environment.culture_cells new_environment.culture_cell(0,0) new_environment.culture_cell(4,3) new_environment.culture_cell(4,4) new_environment.set_num_living_neighbors_for_all_cells new_environment.tick expect(new_environment.cells[0][0].dead).to eq(true) expect(new_environment.cells[4][3].dead).to eq(true) expect(new_environment.cells[4][4].dead).to eq(true) end end context "Rule 2: when living cells have 2 or 3 neighbors" do it "the cells with 2 neighbors continue to live after a tick" do # D_D # _L_ new_environment.culture_cells new_environment.culture_cell(0,0) new_environment.culture_cell(1,1) new_environment.culture_cell(0,2) new_environment.set_num_living_neighbors_for_all_cells new_environment.tick expect(new_environment.cells[0][0].dead).to eq(true) # one neighbor expect(new_environment.cells[1][1].living).to eq(true) # two neighbors expect(new_environment.cells[0][2].dead).to eq(true) # one neighbor end it "the cells with 3 neighbors continue to live after a tick" do # D_D # _L_ # _D_ new_environment.culture_cells new_environment.culture_cell(0,0) new_environment.culture_cell(0,2) new_environment.culture_cell(1,1) new_environment.culture_cell(2,1) new_environment.set_num_living_neighbors_for_all_cells new_environment.tick expect(new_environment.cells[0][0].dead).to eq(true) # one neighbor expect(new_environment.cells[0][2].dead).to eq(true) # one neighbor expect(new_environment.cells[1][1].living).to eq(true) # three neighbors expect(new_environment.cells[2][1].dead).to eq(true) # one neighbor end end context "Rule 3: when living cells have more than three live neighbors" do it "the cells die after one tick" do # LDL # LDL new_environment.culture_cells new_environment.culture_cell(0,0) new_environment.culture_cell(0,1) new_environment.culture_cell(0,2) new_environment.culture_cell(1,0) new_environment.culture_cell(1,1) new_environment.culture_cell(1,2) new_environment.set_num_living_neighbors_for_all_cells new_environment.tick expect(new_environment.cells[0][0].living).to eq(true) # three neighbors expect(new_environment.cells[0][1].dead).to eq(true) # five neighbors expect(new_environment.cells[0][2].living).to eq(true) # three neighbors expect(new_environment.cells[1][0].living).to eq(true) # three neighbors expect(new_environment.cells[1][1].dead).to eq(true) # five neighbors expect(new_environment.cells[1][2].living).to eq(true) # three neighbors end end context "Rule 4: when a dead cell has exactly three live neighbors" do it "the cell becomes a live cell, as if by reproduction" do # _R_ # LLL new_environment.culture_cells new_environment.culture_cell(1,0) new_environment.culture_cell(1,1) new_environment.culture_cell(1,2) new_environment.set_num_living_neighbors_for_all_cells new_environment.tick expect(new_environment.cells[0][1].living).to eq(true) expect(new_environment.cells[1][0].dead).to eq(true) expect(new_environment.cells[1][1].living).to eq(true) expect(new_environment.cells[1][2].dead).to eq(true) end end end context "expansion if needed" do it "expands by a row when expanded by a row" do new_environment.expand_with_new_dead_row expect(new_environment.height).to eq(6) expect(new_environment.cells.length).to eq(6) expect(new_environment.life_at_t_plus_one.length).to eq(6) end it "expands by a column when expanded by a column" do new_environment.expand_with_new_dead_col expect(new_environment.width).to eq(11) new_environment.height.times { |row| expect(new_environment.cells[row].length).to eq(11) } new_environment.height.times { |row| expect(new_environment.life_at_t_plus_one[row].length).to eq(11) } end context "when a 2x2 grid with all living cells is cultured" do # XX XX_ # XX XX_ # ___ it "expands to a 3x3 grid" do square_environment = Environment.new(2,2,1) square_environment.culture_cells square_environment.tick expect(square_environment.height).to eq(3) expect(square_environment.width).to eq(3) expect(square_environment.cells.length).to eq(3) square_environment.height.times { |row| expect(square_environment.cells[row].length).to eq(3) } square_environment.height.times { |row| expect(square_environment.life_at_t_plus_one[row].length).to eq(3) } end end end end
require 'dpd_api' class DeliveryType::Dpd < DeliveryType def is_cost_calc_needed? true end def calculate(order, params = {}) params = params.present? ? params.select{|k, v| Order.delivery_params.include?(k.to_sym)} : order.delivery_params params['weight'] = order.items_weight(true) params['volume'] = order.items_volume(true) dpd = DpdApi.new request = dpd.get_price(params) price = request.present? ? request : nil if price.present? create_request(order, params, price) { price: price, message: '' } else order.delivery_request.delete if order.delivery_request.present? self.errors[:calculate] << 'Доставка по этому адресу компанией DPD не осуществляется. С Вами свяжется наш менеджер для выбора другой транспортной компании.' end end end
Warden::Strategies.add(:ip_address) do #VERA_IP = '::1' VERA_IP = '10.0.1.46' INTERNAL_IP = '10.0.1.' def valid? Rails.logger.info "Warden checking strategy ip_address against #{request.ip}" request.ip == VERA_IP #request.ip[0..(INTERNAL_IP.length-1)] == INTERNAL_IP end def authenticate! if request.ip == VERA_IP u = User.find_by(username: 'vera') u ? success!(u) : fail! end end end
require 'mqtt' require 'i2c' require 'fileutils' require 'json' require 'pp' require 'date' require 'yaml' class RasPiIotShadow attr_accessor :airconmode, :turnOnSignal, :turnOffSignal def initialize(path, address = 0x27, airconmode= 0, turnOnSignal=nil, turnOffSignal=nil) #i2c @device = I2C.create(path) @address = address @time = 0 @temp = 0 @humidity = 0 #airconSetting @setTemp = 20 @airconmode = airconmode #TunrnedOnAircon -> 1, TurnedOffAircon -> 0 iotconfig = YAML.load_file("iot.yml") #toKinesis and tempChecker @host = iotconfig["iotShadowConfig"]["host"] @topic = iotconfig["iotShadowConfig"]["topic"] @port = iotconfig["iotShadowConfig"]["port"] @certificate_path = iotconfig["iotShadowConfig"]["certificatePath"] @private_key_path = iotconfig["iotShadowConfig"]["privateKeyPath"] @root_ca_path = iotconfig["iotShadowConfig"]["rootCaPath"] @thing = iotconfig["iotShadowConfig"]["thing"] #turnOnAircon and turnOffAircon @topicTurnedOn = iotconfig["airconConfig"]["topicOn"] @topicTurnedOff = iotconfig["airconConfig"]["topicOff"] #turnOn or turnOff command for Advanced remote controller @turnOnSignal = turnOnSignal @turnOffSignal = turnOffSignal end def waitTurnOn MQTT::Client.connect(host:@host, port:@port, ssl: true, cert_file:@certificate_path, key_file:@private_key_path, ca_file: @root_ca_path) do |client| puts "waiting turnonCommand.." client.subscribe(@topicTurnedOn) client.get #wait ios-app command end #MQTT end end #def turnOnAircon end def turnOnAircon on = system("bto_advanced_USBIR_cmd -d #{@turnOnSignal}") if on puts "send TurnOn command" end end #def turnOnAircon end end #class RasPiIotShadow end #Following are processed codes sensingWithRaspi = RasPiIotShadow.new('/dev/i2c-1') Process.daemon(nochdir = true, noclose = nil) #turnOnAircon process loop do sensingWithRaspi.waitTurnOn sensingWithRaspi.turnOnSignal = File.read("turnOn.txt") sensingWithRaspi.turnOnAircon end
FactoryBot.define do factory :institution do sequence(:name) {|n| "Institution #{n}"} end end
require 'spec_helper' RSpec.describe SolidusBraintree::BraintreeCheckoutHelper do let!(:store) { create :store } let(:braintree_configuration) { {} } before do store.braintree_configuration.update(braintree_configuration) end describe '#venmo_button_style' do subject { helper.venmo_button_style(store) } context 'when the venmo button is white and has a width of 280' do let(:braintree_configuration) { { preferred_venmo_button_width: '280', preferred_venmo_button_color: 'white' } } it 'returns a hash of the width and color' do expect(subject).to eq({ width: '280', color: 'white' }) end end context 'when the venmo button is blue and has a width of 375' do let(:braintree_configuration) { { preferred_venmo_button_width: '375', preferred_venmo_button_color: 'blue' } } it 'returns a hash of the width and color' do expect(subject).to eq({ width: '375', color: 'blue' }) end end end describe '#venmo_button_width' do subject { helper.venmo_button_asset_url(style, active: active) } context 'when the given style color is white and width is 280, and the given active is false' do let(:style) { { width: '280', color: 'white' } } let(:active) { false } it 'returns the correct url' do expect(subject).to match(%r[\A/assets/solidus_braintree/venmo/venmo_white_button_280x48-.+\.svg]) end end context 'when the given style color is white and width is 280, and the given active is true' do let(:style) { { width: '280', color: 'white' } } let(:active) { true } it 'returns the correct url' do expect(subject).to match(%r[\A/assets/solidus_braintree/venmo/venmo_active_white_button_280x48-.+\.svg]) end end context 'when the given style color is blue and width is 320, and the given active is false' do let(:style) { { width: '320', color: 'blue' } } let(:active) { false } it 'returns the correct url' do expect(subject).to match(%r[\A/assets/solidus_braintree/venmo/venmo_blue_button_320x48-.+\.svg]) end end context 'when the given style color is blue and width is 320, and the given active is true' do let(:style) { { width: '320', color: 'blue' } } let(:active) { true } it 'returns the correct url' do expect(subject).to match(%r[\A/assets/solidus_braintree/venmo/venmo_active_blue_button_320x48-.+\.svg]) end end end end
module LoanrecordsControllerConcerns extend ActiveSupport::Concern included do load_and_authorize_resource before_action :authenticate_user! end def index if user_signed_in? && current_user.has_role?(:admin) @loanrecords = Loanrecord.all else @loanrecords = Loanrecord.includes(:user).includes(:stock).where(user_id: current_user.id) end respond_to do |format| format.html format.js format.xlsx{ response.headers['Content-Disposition'] = 'attachment; filename="all_loanrecords.xlsx"' } end end def show @report = Report.includes(:stock).includes(stock: :item).find_by_id(params[:id]) end def new @report = Report.new @stocks = Item.find_by_id(params[:item_id]).stocks end def create s = Stock.find_by_id(loanrecord_params[:stock_id]) if s.loanrecords.where(status: ['on_loan','pending','overdue']).count > 1 flash[:danger] = "Error, stock is already on loan" redirect_to :back return elsif s.item.check_authorization(current_user) == false flash[:danger] = "Error, you are not authorized to loan this stock" redirect_to :back return end @loanrecord = current_user.loanrecords.build(loanrecord_params) @loanrecord.expect_return_date = Time.now + 1.month @loanrecord.status = :pending if @loanrecord.save! stock = Stock.find_by_id(loanrecord_params[:stock_id]) if stock.present? stock.is_on_loan = true stock.save! end flash[:success] = "Loan record created!" redirect_to loanrecords_path else render 'static_pages/home' end end def loanrecord_params params.require(:loanrecord).permit(:stock_id, :status, :user_id, :return_date, :expect_return_date) end end
# frozen_string_literal: true require 'spec_helper' require './lib/fusuma/config.rb' require './lib/fusuma/plugin/executors/executor.rb' require './lib/fusuma/plugin/events/event.rb' module Fusuma module Plugin module Executors RSpec.describe Executor do before { @executor = Executor.new } describe '#execute' do it do expect { @executor.execute('dummy') }.to raise_error(NotImplementedError) end end describe '#executable?' do it do expect { @executor.executable?('dummy') }.to raise_error(NotImplementedError) end end end class DummyExecutor < Executor def execute(event) # stdout puts event.record.index.keys.last.symbol if executable?(event) end def executable?(event) event.tag == 'dummy' end end RSpec.describe DummyExecutor do before do index = Config::Index.new(:dummy_text) record = Events::Records::IndexRecord.new(index: index) @event = Events::Event.new(tag: 'dummy', record: record) @executor = DummyExecutor.new end around do |example| ConfigHelper.load_config_yml = <<~CONFIG plugin: executors: dummy_executor: dummy: dummy CONFIG example.run Config.custom_path = nil end describe '#execute' do it { expect { @executor.execute(@event) }.to output("dummy_text\n").to_stdout } context 'without executable' do before do allow(@executor).to receive(:executable?).and_return false end it { expect { @executor.execute(@event) }.not_to output("dummy_text\n").to_stdout } end end describe '#executable?' do it { expect(@executor.executable?(@event)).to be_truthy } end describe '#config_params' do it { expect(@executor.config_params).to eq(dummy: 'dummy') } end end end end end
require 'spec_helper' describe ScannerExtensions::Helpers::OobDnsClient do it 'compatible with oob-dns service' do ScannerExtensions::Helpers::OobDnsClient.config = { 'host' => 'oob-dns', 'port' => '8080' } token = ScannerExtensions::Helpers::OobDnsClient.create array = ScannerExtensions::Helpers::OobDnsClient.get token expect(array).to eq [] begin Resolv::DNS.new( nameserver_port: [['oob-dns', 5053]] ).getresources(token, Resolv::DNS::Resource::IN::A) rescue end array = ScannerExtensions::Helpers::OobDnsClient.get token expect(array.size).to be > 0 end end
class UserSession < Authlogic::Session::Base validate :check_if_verified private def check_if_verified if attempted_record and attempted_record.verified == false errors.add(:base, "You have not yet verified your account. \ Please reference your email for instructions") end end end
class AddNamHocToLops < ActiveRecord::Migration[5.1] def change add_column :lops, :namhoc, :string end end
require 'spec_helper' describe "Users" do before(:each) do @attr = { :name => "$19 for Medium-Sized, Personalized Bagguettes Photo Bag ($41 Value)", :price => 1700, :value => 4100, :starting_date => "01/14/2011", :days_available => 5, :num_available => 200, :num_purchased => 138, :num_needed_to_unlock => 15, :blurb => "Without a stylish cosmetic bag, women are forced to wear beer helmets of lip gloss and bandoleers of mascara. Enjoy fashion and function with today's Groupon: for $19, today's deal gets you a personalized, medium-sized cosmetic bag from Bagettes ($41 value including shipping). Bagettes allows customers to personalize their bags by incorporating their own photos and text into the design. Constructed from satin fabric and featuring a black nylon lining, the medium cosmetic bag is 8x5, giving it the volume to handle makeup, toiletries, and several hamsters. Images are embedded into the fibers of the bags rather than applied superficially to the surface, helping prevent fading and peeling over time and making the bags practical and durable ways to preserve special moments and to broadcast hilarious personal slogans. Images, from endearing shots of family members and pets to psychedelic portraiture of famous flightless birds, are submitted using the Bagettes website and can be cropped, resized, and rotated to fit the customer's precise specifications. The site also allows the addition of text to any image, with more than 200 fonts with which to write special messages, personalized captions, and high-level cryptography. Because of their highly personal and customizable nature, Bagettes bags make excellent gifts for mothers, bridesmaids, and hobbyists who collect bags printed with images of other bags. The value of today's Groupon can also be applied toward the purchase of a more expensive bag. Additional shipping and handling charges may apply for upgrades.", :expires => "07/14/2011", :location => "www.bagettes.com", :company => "Baggettes" } @deal = Deal.create!(@attr) end describe "signup" do describe "failure" do it "should not make a new user" do lambda do visit signup_path fill_in "Name", :with => "" fill_in "Email", :with => "" fill_in "Password", :with => "" fill_in "Confirmation", :with => "" click_button response.should render_template('users/new') response.should have_selector("div#error_explanation") end.should_not change(User, :count) end end describe "success" do it "should make a new user" do lambda do visit signup_path fill_in "Name", :with => "Example User" fill_in "Email", :with => "user@example.com" fill_in "Password", :with => "foobar" fill_in "Confirmation", :with => "foobar" click_button response.should have_selector("div.flash.success", :content => "Welcome") response.should render_template('/') end.should change(User, :count).by(1) end end end describe "sign in/out" do describe "failure" do it "should not sign a user in" do visit signin_path fill_in :email, :with => "" fill_in :password, :with => "" click_button response.should have_selector("div.flash.error", :content => "Invalid") end end describe "success" do it "should sign a user in and out" do user = Factory(:user) visit signin_path fill_in :email, :with => user.email fill_in :password, :with => user.password click_button controller.should be_signed_in click_link "Sign out" controller.should_not be_signed_in end end end end
class AddApiIdToMotels < ActiveRecord::Migration[5.1] def change add_column :motels, :api_motel_id, :integer end end
class Url < ActiveRecord::Base validates :long_url, presence: true, format: URI::regexp(%w(http https)) validates :short_url, presence:true, uniqueness: true def self.reterive_short_url(long_url) url = Url.find_by(:long_url => long_url ) if url == nil return nil else return url.short_url end end end
class AddDatesToConfigurations < ActiveRecord::Migration def change add_column :configurations, :created_at, :datetime add_column :configurations, :updated_at, :datetime end end
class Area < ActiveRecord::Base # require 'carrierwave/orm/activerecord' belongs_to :universe has_many :characters has_many :areas belongs_to :area TYPES = %w(Kingdom City Place) mount_uploader :map, MapUploader self.inheritance_column = :changing_the_self_inheritance_column def cities if self.type = "Kingdom" Area.where(type: "City").where(area_id: self.id) else raise "Only a kingdom can have cities" end end def places if self.type = "City" Area.where(type: "Place").where(area_id: self.id) else raise "Only a city can have places" end end def area_name_for_lists "#{name}" end class << self # returns the associated cities/places/kingdoms def for(model) TYPES.each_with_index do |type, index| if model.type == type return [] if index == 0 return Area.send(TYPES[index-1].downcase.pluralize) end end Area.all end def cities Area.where(type: 'City') end def places Area.where(type: 'Place') end def kingdoms Area.where(type: 'Kingdom') end end validates_presence_of :name validates_length_of :name, :maximum => 128, :too_long => "Can't be more than 128 characters." end
# encoding: utf-8 # copyright: 2018, Chef CFT control "gdpr-benchmark-windiws-firewall-ensure-on" do title "Ensure Windows Firewall is set to On" desc "For GDPR compliance we need Windows Firewall with Advanced Security use the settings for this profile to filter network traffic." impact 1.0 describe registry_key("HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\WindowsFirewall\\DomainProfile") do it { should have_property "EnableFirewall" } end describe registry_key("HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\WindowsFirewall\\DomainProfile") do its("EnableFirewall") { should cmp == 1 } end end control "gdpr-benchmark-windiws-firewall-block-inbound-on" do title "Ensure we block inbound unless overriden" desc "This setting determines the behavior for inbound connections that do not match an inbound firewall rule. The default behavior is to block connections unless there are firewall rules to allow the connection." impact 1.0 describe registry_key("HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\WindowsFirewall\\PrivateProfile") do it { should have_property "DefaultInboundAction" } end describe registry_key("HKEY_LOCAL_MACHINE\\Software\\Policies\\Microsoft\\WindowsFirewall\\PrivateProfile") do its("DefaultInboundAction") { should cmp == 1 } end end
# frozen_string_literal: true require 'stannum/constraints' module Stannum::Constraints # An Identity constraint checks for the exact object given. # # @example Using an Identity constraint # string = 'Greetings, programs!' # constraint = Stannum::Constraints::Identity.new(string) # # constraint.matches?(nil) #=> false # constraint.matches?('a string') #=> false # constraint.matches?(string.dup) #=> false # constraint.matches?(string) #=> true class Identity < Stannum::Constraints::Base # The :type of the error generated for a matching object. NEGATED_TYPE = 'stannum.constraints.is_value' # The :type of the error generated for a non-matching object. TYPE = 'stannum.constraints.is_not_value' # @param expected_value [Object] The expected object. # @param options [Hash<Symbol, Object>] Configuration options for the # constraint. Defaults to an empty Hash. def initialize(expected_value, **options) @expected_value = expected_value super(expected_value: expected_value, **options) end # @return [Object] the expected object. attr_reader :expected_value # Checks that the object is the expected value. # # @return [true, false] true if the object is the expected value, otherwise # false. # # @see Stannum::Constraint#matches? def matches?(actual) expected_value.equal?(actual) end alias match? matches? end end
class PhoneNumber < ApplicationRecord belongs_to :lead validates_format_of :number, :with => /\(?[0-9]{3}\)?-[0-9]{3}-[0-9]{4}/, :message => "- must be in xxx-xxx-xxxx format." end
Apipie.configure do |config| config.app_name = "Reveille" config.api_base_url = "/api" config.doc_base_url = "/doc" # were is your API defined? config.api_controllers_matcher = "#{Rails.root}/app/controllers/api/**/*.rb" config.default_version = "v1" config.use_cache = Rails.env.production? config.markup = Apipie::Markup::Markdown.new if Rails.env.development? and defined? Maruku end
class CreateClassTemplateClassTypes < ActiveRecord::Migration def change remove_index :class_templates, :clazz_type_id remove_column :class_templates, :clazz_type_id create_table :class_template_class_types do |t| t.integer :class_template_id t.integer :clazz_type_id t.timestamps null: false end add_index :class_template_class_types, :class_template_id add_index :class_template_class_types, :clazz_type_id end end
require "lita" module Lita module Handlers class Redmine < Handler config :type, default: :redmine # valid values: [:chiliproject, :redmine] config :url config :apikey route /redmine\s+(\d+)/, :issue, help: { "redmine <issue #>" => "Displays issue url and subject" } def issue(response) if config.url redmine_url = config.url.chomp("/") else raise "Redmine URL must be defined ('config.handlers.redmine.url')" end if config.apikey apikey = config.apikey else raise "Redmine API key must be defined ('config.handlers.redmine.apikey')" end case config.type when :redmine apikey_header = "X-Redmine-API-Key" when :chiliproject apikey_header = "X-ChiliProject-API-Key" else raise "Redmine type must be :redmine (default) or :chiliproject ('config.handlers.redmine.type')" end issue_id = response.matches.flatten.first issue_url = URI.parse("#{redmine_url}/issues/#{issue_id}") issue_json_url = "#{issue_url}.json" http_resp = http.get(issue_json_url, {}, { apikey_header => apikey }) case http_resp.status when 200 resp = MultiJson.load(http_resp.body) message = "#{issue_url} : #{resp["issue"]["subject"]}" when 404 message = "Issue ##{issue_id} does not exist" else raise "Failed to fetch #{issue_json_url} (#{http_resp.status})" end response.reply(message) rescue Exception => e response.reply("Error: #{e.message}") end end Lita.register_handler(Redmine) end end
class AddIndexToSocks < ActiveRecord::Migration def self.up add_index "socks", :bundle_id add_index "socks", :pod_id end def self.down remove_index "socks", :bundle_id add_index "socks", :pod_id end end
class HashTag < ActiveRecord::Base # attr_accessible :title, :body belongs_to :post def self.trending self.order("count DESC").limit(10) end end
require 'spec_helper' describe AddressesController do let!(:address) { create(:address) } let(:valid_params) { attributes_for(:address, cidr: "120.4.4.1/12") } let(:invalid_params) {{ cidr: "not/valid" }} describe "GET show" do it "redirects to edit" do get :show, id: address.id expect(response).to redirect_to(edit_address_path(address.id)) end end describe "GET index" do it "assigns the addresses" do get :index expect(response).to be_ok expect(assigns(:addresses)).to eq([address]) end end describe "GET new" do it "assigns" do get :new expect(response).to be_ok expect(assigns(:address)).to be_new_record end end describe "GET edit" do it "assigns the address" do get :edit, id: address.id expect(response).to be_ok expect(assigns(:address)).to eq address end end describe "GET lookup" do it "displays the index form" do get :lookup expect(response).to be_ok end end describe "GET whitelisted" do it "returns a json true response when whitelisted" do get :whitelisted, ip_address: "127.0.0.1" body = JSON.parse(response.body) expect(body["whitelisted"]).to eq(true) end it "returns a json false response when not whitelisted" do get :whitelisted, ip_address: "1.1.1.0" body = JSON.parse(response.body) expect(body["whitelisted"]).to eq(false) end end describe "POST create" do it "creates a new address" do expect{ post :create, address: valid_params } .to change{ Address.count }.by(1) expect(Address.last.cidr).to eq valid_params[:cidr] end it "redirects to index on success" do post :create, address: valid_params expect(response).to redirect_to addresses_path end it "rerenders on validation errors" do post :create, address: invalid_params expect(response).to be_ok expect(response).to render_template("new") expect(assigns(:address)).to be_new_record end end describe "PATCH update" do it "creates a new address" do patch :update, id: address.id, address: valid_params expect(address.reload.cidr).to eq valid_params[:cidr] end it "redirects to index on success" do patch :update, id: address.id, address: valid_params expect(response).to redirect_to addresses_path end it "rerenders on validation errors" do patch :update, id: address.id, address: invalid_params expect(response).to be_ok expect(response).to render_template("edit") expect(assigns(:address)).to eq address end end describe "DELETE destroy" do it "deletes the address" do expect { delete :destroy, id: address.id }.to change{Address.count}.by(-1) end it "redirects to index on success" do delete :destroy, id: address.id expect(response).to redirect_to addresses_path end end end
require 'rails_helper' feature "登録画面" do background do @task=Task.create!(title: 'test', memo: 'hogehoge') visit new_task_path end scenario 'コンテンツ一覧' do expect(page).to have_content 'タスク登録画面です。' expect(page).to have_content 'タスク名 : ' expect(page).to have_content '終了期限 : ' expect(page).to have_content 'メモ : ' expect(page).to have_content '優先度 : ' expect(page).to have_content '進捗 : ' expect(page).to have_content 'ラベル : ' end scenario 'CHECKボタン' do expect(page).to have_button 'CHECK' click_on 'CHECK' expect(page).to have_content '新しいタスクが登録されました。' end end
# frozen_string_literal: true # handle postgis adapter as if it were postgresql, # only override the adapter_method used for initialization require 'apartment/adapters/postgresql_adapter' module Apartment module Tenant def self.postgis_adapter(config) postgresql_adapter(config) end end end
require 'pony' module MailUtils def self.send_invitation(email, name, url) Pony.mail :to => email, :from => ENV['MAIL_USERNAME'], :subject => "Hola!, #{name}!", :body => "Tu entrada al evento la puedes ver aqui: #{url}", :via => :smtp, :via_options => { :address => ENV['MAIL_DOMAIN'], :port => '587', :enable_starttls_auto => true, :user_name => ENV['MAIL_USERNAME'], :password => ENV['MAIL_PASSWORD'], :authentication => :plain, # :plain, :login, :cram_md5, no auth by default :domain => ENV['HELO_DOMAIN'] # the HELO domain provided by the client to the server } end end
namespace :db do desc "Fill database with sample data" task populate: :environment do admin = User.create!(name: "Admin", email: "admin@imagstech.com", password: "adminfoobar", password_confirmation: "adminfoobar", role: "Admin") end end