text
stringlengths
10
2.61M
# frozen_string_literal: true require 'rails_helper' RSpec.describe Notifier, type: :mailer do describe 'instructions' do let(:user) { create(:user) } let(:mail) { described_class.cv(user).deliver_now } it 'renders the subject' do expect(mail.subject).to eq('CV review') end it 'renders the receiver email' do expect(mail.to).to eq(['web@proektmarketing.ru']) end it 'renders the sender email' do expect(mail.from).to eq(['maxim@just4.ru']) end it 'assigns @name' do expect(mail.body.encoded).to match(user.first_name) end it 'assigns @cv_link' do expect(mail.body.encoded) .to match(user.cv_link) end it 'assigns @cv_project_link' do expect(mail.body.encoded) .to match(user.cv_project_link) end end end
require 'sinatra/base' require 'sinatra/param/version' require 'time' require 'date' module Sinatra module Param Boolean = :boolean class InvalidParameterError < StandardError attr_reader :type, :value MESSAGES = { required: 'is required.', blank: 'is blank.', is: 'is not %s', in: 'not in %s', max: 'more than %s', min: 'less than %s', min_length: 'length less than %s', max_length: 'length more than %s', } def initialize type, value @type = type @value = value end def message name "Parameter #{name} #{MESSAGES[type] % value.to_s}" end def to_json name, encoder if encoder encoder.encode(to_hash(name)) else to_hash(name).to_json end end def to_hash name {message: message(name)} end end def param(name, type, options = {}) name = name.to_s return unless params.member?(name) or present?(options[:default]) or options[:required] begin params[name] = coerce(params[name], type, options) params[name] = options[:default] if (params[name].nil? || params[name] == '') and options[:default] if options[:transform] options[:transform] = [options[:transform]] unless [options[:transform]].is_a?(Array) params[name] = params[name].send(*options[:transform]) end validate!(params[name], options) rescue InvalidParameterError => error response_body = if content_type and content_type.match(mime_type(:json)) error.to_json(name, settings.respond_to?(:json_encoder) ? settings.json_encoder : false) else error.message(name) end halt 400, response_body end end def one_of(*names) count = 0 names.each do |name| if params[name] and present?(params[name]) count += 1 next unless count > 1 error = "Parameters #{names.join(', ')} are mutually exclusive" if content_type and content_type.match(mime_type(:json)) error = {message: error}.to_json end halt 400, error end end end private def coerce(param, type, options = {}) begin return nil if param.nil? return param if (param.is_a?(type) rescue false) return Integer(param) if type == Integer return Float(param) if type == Float return String(param) if type == String return Time.parse(param) if type == Time return Date.parse(param) if type == Date return DateTime.parse(param) if type == DateTime return Array(param.split(options[:delimiter] || ",")) if type == Array return Hash[param.split(options[:delimiter] || ",").map{|c| c.split(options[:separator] || ":")}] if type == Hash return (/(false|f|no|n|0)$/i === param.to_s ? false : (/(true|t|yes|y|1)$/i === param.to_s ? true : nil)) if type == TrueClass || type == FalseClass || type == Boolean return nil rescue raise InvalidParameterError.new(:is, type) end end def validate!(param, options) options.each do |key, value| case key when :required raise InvalidParameterError.new(:required, value) if value && param.nil? when :blank raise InvalidParameterError.new(:blank, value) if !value && case param when String !(/\S/ === param) when Array, Hash param.empty? else param.nil? end when :is raise InvalidParameterError.new(:is, value) unless value === param when :in, :within, :range raise InvalidParameterError.new(:in, value) unless param.nil? || case value when Range value.include?(param) else Array(value).include?(param) end when :min raise InvalidParameterError.new(:min, value) unless param.nil? || value <= param when :max raise InvalidParameterError.new(:max, value) unless param.nil? || value >= param when :min_length raise InvalidParameterError.new(:min_length, value) unless param.nil? || value <= param.length when :max_length raise InvalidParameterError.new(:max_length, value) unless param.nil? || value >= param.length end end end # ActiveSupport #present? and #blank? without patching Object def present?(object) !blank?(object) end def blank?(object) object.respond_to?(:empty?) ? object.empty? : !object end end helpers Param end
module Fog module Google class Pubsub class Real # Delete a topic on the remote service. # # @param topic_name [#to_s] name of topic to delete # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/delete def delete_topic(topic_name) @pubsub.delete_topic(topic_name) end end class Mock def delete_topic(_topic_name) raise Fog::Errors::MockNotImplemented end end end end end
class ReviewPic < ApplicationRecord belongs_to :review scope :filter_by_page, -> (page_param) { page(page_param).per(6) } end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "versatile_rjs" s.version = "0.1.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Kevin IMAI TOYODA"] s.date = "2012-05-01" s.description = "VersatileRJS: Enables RJS with Rails(3.1 or higher) and jQuery.\n\n\n" s.email = "condor1226@gmail.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "History.txt", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "init.rb", "lib/versatile_rjs.rb", "lib/versatile_rjs/container.rb", "lib/versatile_rjs/page.rb", "lib/versatile_rjs/proxy.rb", "lib/versatile_rjs/proxy/default_responder.rb", "lib/versatile_rjs/proxy/each_proxy.rb", "lib/versatile_rjs/proxy/element_by_id_proxy.rb", "lib/versatile_rjs/proxy/element_proxy.rb", "lib/versatile_rjs/proxy/element_set_proxy.rb", "lib/versatile_rjs/proxy/expression_proxy.rb", "lib/versatile_rjs/proxy/framework_dependent.rb", "lib/versatile_rjs/proxy/jquery.rb", "lib/versatile_rjs/proxy/jquery/each_proxy.rb", "lib/versatile_rjs/proxy/jquery/element_by_id_proxy.rb", "lib/versatile_rjs/proxy/jquery/element_proxy.rb", "lib/versatile_rjs/proxy/jquery/element_set.rb", "lib/versatile_rjs/proxy/jquery/element_set_proxy.rb", "lib/versatile_rjs/proxy/jquery/selectable.rb", "lib/versatile_rjs/proxy/jquery/selector_proxy.rb", "lib/versatile_rjs/proxy/selectable.rb", "lib/versatile_rjs/proxy/selector_proxy.rb", "lib/versatile_rjs/railtie.rb", "lib/versatile_rjs/template_handler.rb", "lib/versatile_rjs/to_function_ext.rb", "lib/versatile_rjs/utils.rb", "lib/versatile_rjs/utils/.gitignore", "script/console", "script/destroy", "script/generate", "spec/spec_helper.rb", "spec/versatile_rjs_spec.rb", "versatile_rjs.gemspec" ] s.homepage = "http://github.com/condor/versatile_rjs" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.15" s.summary = "VersatileRJS: Enables RJS with Rails(3.1 or higher) and jQuery." if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rails>, [">= 3.1.0"]) s.add_development_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_development_dependency(%q<cucumber>, [">= 0"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_development_dependency(%q<rcov>, [">= 0"]) s.add_development_dependency(%q<jruby-openssl>, [">= 0"]) else s.add_dependency(%q<rails>, [">= 3.1.0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<cucumber>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<jruby-openssl>, [">= 0"]) end else s.add_dependency(%q<rails>, [">= 3.1.0"]) s.add_dependency(%q<rspec>, ["~> 2.3.0"]) s.add_dependency(%q<cucumber>, [">= 0"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.4"]) s.add_dependency(%q<rcov>, [">= 0"]) s.add_dependency(%q<jruby-openssl>, [">= 0"]) end end
describe StarWars::ImportPeople do describe "#call" do subject(:call) { described_class.call } before do allow(StarWarsAPI::Swapi::Request).to receive(:new).and_return swapi_api allow(swapi_api).to receive(:get_people).with(page: 1).once.and_return response allow(swapi_api).to receive(:get_people).with(page: 2).once.and_return OpenStruct.new(found?: false) end let(:swapi_api) { instance_double(StarWarsAPI::Swapi::Request) } let(:person) { Person.first } let(:response) do OpenStruct.new( found?: true, data: OpenStruct.new( results: [ OpenStruct.new( name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", eye_color: "blue", birth_year: "19BBY", gender: "male", homeworld: "https://swapi.dev/api/planets/1/", films: %w[ https://swapi.dev/api/films/1/ https://swapi.dev/api/films/2/ https://swapi.dev/api/films/3/ https://swapi.dev/api/films/6/ ], species: ["https://swapi.dev/api/species/1/"], vehicles: %w[https://swapi.dev/api/vehicles/14/ https://swapi.dev/api/vehicles/30/], starships: %w[https://swapi.dev/api/starships/12/ https://swapi.dev/api/starships/22/], created: "2014-12-09T13:50:51.644000Z", edited: "2014-12-20T21:17:56.891000Z", url: "https://swapi.dev/api/people/1/" ) ] ) ) end let(:response_attributes) do response.data.results.first.to_h.slice( :name, :height, :mass, :hair_color, :skin_color, :eye_color, :birth_year, :gender, :url ) end let!(:planet) do create(:planet, url: "https://swapi.dev/api/planets/1/") end let!(:species) do [create(:specie, url: "https://swapi.dev/api/species/1/")] end let!(:starships) do [ create(:starship, url: "https://swapi.dev/api/starships/12/"), create(:starship, url: "https://swapi.dev/api/starships/22/") ] end it "changes person count on database" do expect { call }.to change(Person, :count).by 1 end it "imports person with the given attributes" do call expect(person).to have_attributes(response_attributes) end it "imports person with planet association" do call expect(person.homeworld).to eq planet end it "imports person with starships association" do call expect(person.starships).to eq starships end it "imports person with species association" do call expect(person.species).to eq species end end end
class RemoveFieldsFromUsers < ActiveRecord::Migration[6.1] # def change # remove_column :users, :avatar_file_name # remove_column :users, :avatar_content_type # remove_column :users, :avatar_file_size # remove_column :users, :avatar_updated_at # end end
require 'csv' CSV.readlines(__FILE__).each { |i| puts i } @students = [] # an empty array accessible to all methods def print_header puts "The students of Villains Academy".center(60) puts "-------------".center(60) end def print_students_list if @students.count <= 0 return end @students.each_with_index do |student, index| puts "#{student[:name]} (#{student[:cohort]} cohort)".center(60) end end def print_footer if @students.count <= 0 return end if @students.count == 1 puts "Overall, we have #{@students.count} great student".center(60) else puts "Overall, we have #{@students.count} great students".center(60) end end def show_students print_header print_students_list print_footer end def input_students puts "Please enter the name of the student".center(60) puts "(to finish at any point, just hit return twice)".center(60) name = STDIN.gets.gsub(/\n/,"") puts "Enter their cohort (please spell perfectly!)".center(60) cohort = STDIN.gets.gsub(/\n/,"") # https://github.com/makersacademy/problem-solving/issues/102#issuecomment-315815931 # while the name is not empty, repeat this code while !name.empty? do if cohort == "" cohort = "november" end add_students_to_arr(name, cohort) if @students.count == 1 "Now we have #{@students.count} student".center(60) else "Now we have #{@students.count} students".center(60) end name = STDIN.gets.chomp end @students end def print_menu menu_choices = ["1. Input the students", "2. Show the students", "3. Save your list", "4. Load a list", "9. Exit"] puts menu_choices end def process(selection) response = ["You picked ","1","2","3","4"] case selection when "1" puts "#{response[0] + response[1]}" input_students when "2" puts "#{response[0] + response[2]}" show_students when "3" puts "#{response[0] + response[3]}" save_students_to_file when "4" puts "#{response[0] + response[4]}" load_students_from_file when "9" then exit else puts "I don't know what you mean, try again" end end def interactive_menu loop do print_menu process(gets.chomp) end end def save_students_to_file # open the file for writing puts "You are about to save your list, please give it a name (please add .csv etc.):" file = CSV.open("#{gets.chomp}", "w") do |file| @students.each do |student| student_data = [student[:name], student[:cohort]] csv_line = student_data.join(",") file.puts csv_line end # puts "Saved #{@students.count} students." end end def load_students_from_file puts "Name the file you want to add (please add its extension!):" filename = gets.chomp file = CSV.foreach(filename, "r") do |file| file.readlines.each do |line| name, cohort = line.chomp.split(',') add_students_to_arr(name, cohort) end # puts "Saved #{@students.count} students." end end def add_students_to_arr(name, cohort) @students << {name: name, cohort: cohort.to_sym} end def try_load_students_from_file if !!ARGV filename = "students.csv" else filename = ARGV.first end return if filename.nil? # get out of the method if it isn't given << important! if File.exists?(filename) # load_students_from_file(filename) puts "Loaded #{@students.count} from #{filename}" else puts "Sorry, #{filename} doesn't exist." exit end end try_load_students_from_file interactive_menu # Past methods # count = 1 # while count <= 11 # students.each_with_index do |student, index| # puts "#{index + 1}. #{student[:name]} (#{student[:cohort]} cohort) #{student[:height]}, #{student[:birthplace]}" # count = count + 1
require 'minitest/autorun' require_relative '../../../lib/arcade/intro/the_journey_begins' class TheJourneyBeginsTest < Minitest::Test def setup @this_world = TheJourneyBegins.new end def test_add assert_equal 3, @this_world.add(1, 2) assert_equal (-37), @this_world.add(2, -39) assert_equal (-2000), @this_world.add(-1000, -1000) end def test_century_from_year assert_equal 20, @this_world.century_from_year(1905) assert_equal 17, @this_world.century_from_year(1700) assert_equal 1, @this_world.century_from_year(8) end def test_check_palindrome assert_equal true, @this_world.check_palindrome("aabaa") assert_equal false, @this_world.check_palindrome("zzzazzazz") assert_equal true, @this_world.check_palindrome("z") end end
class Region attr_accessor :name def initialize(name, population, area_size, continent) self.name = name self.population = population self.area_size = area_size self.continent = continent end def greeting puts name_info + population_info end def more_densely_populated?(other_region) result = population_density > other_region.population_density ? 'more' : 'less' puts "#{name} is #{result} densely populated than #{other_region.name}." end def the_same_continent?(other_region) if continent.eql?(other_region.continent) puts "#{name} and #{other_region.name} lie in the same continent." else puts "#{name} and #{other_region.name} lie in the different continents." end end def can_be_crowdy? if self.consider_as_densely_populated? puts "#{name} can be crowdy." else "There is enough space in the #{name}." end end protected attr_accessor :continent def name_info "Hello, I'm #{name}!" end private attr_accessor :population, :area_size def population_info " #{population} people live here." end def population_density population / area_size end def consider_as_densely_populated? population_density > self.class::HIGH_POPULATION_DENSITY end end class Country < Region HIGH_POPULATION_DENSITY = 300 def own_greeting puts "The country name: #{name}." + population_info end end class City < Region HIGH_POPULATION_DENSITY = 3000 def own_greeting puts name_info + " The population: #{population} people." end end # initialization wroclaw = City.new('Wrocław', 638_000, 293, 'Europe') san_francisco = City.new('San Francisco', 884_000, 121, 'Northern America') poland = Country.new('Poland', 38_000_000, 312_000, 'Europe') # I section wroclaw.greeting poland.greeting # II section wroclaw.name_info wroclaw.population_info # III section wroclaw.own_greeting poland.own_greeting # IV section wroclaw.more_densely_populated?(san_francisco) wroclaw.the_same_continent?(san_francisco) san_francisco.can_be_crowdy?
=begin Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. =end def fibonacci(n) a, b = 1, 2 while b < n do a, b = b, b+a (results ||= []) << b end results end sum = 0 fibonacci( 4e6 ).each do |i| sum += i if i%2 == 0 end puts sum
require "codeunion/http_client" module CodeUnion # Intent-revealing methods for interacting with Github with interfaces # that aren't tied to the api calls. class GithubAPI def initialize(access_token) @access_token = access_token @http_client = HTTPClient.new("https://api.github.com") end def create_issue(title, content, repository) @http_client.post("repos/#{repository}/issues", { "title" => title, "body" => content }, { "access_token" => @access_token }) end end end
require 'test_helper' class JsonSamplesControllerTest < ActionController::TestCase setup do @json_sample = json_samples(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:json_samples) end test "should get new" do get :new assert_response :success end test "should create json_sample" do assert_difference('JsonSample.count') do post :create, json_sample: { content: @json_sample.content, title: @json_sample.title } end assert_redirected_to json_sample_path(assigns(:json_sample)) end test "should show json_sample" do get :show, id: @json_sample assert_response :success end test "should get edit" do get :edit, id: @json_sample assert_response :success end test "should update json_sample" do put :update, id: @json_sample, json_sample: { content: @json_sample.content, title: @json_sample.title } assert_redirected_to json_sample_path(assigns(:json_sample)) end test "should destroy json_sample" do assert_difference('JsonSample.count', -1) do delete :destroy, id: @json_sample end assert_redirected_to json_samples_path end end
module NotificationsHelper def notification_icon(notification) if notification.disabled? content_tag :i, nil, class: 'icon-volume-off cred' elsif notification.participating? content_tag :i, nil, class: 'icon-volume-down cblue' elsif notification.watch? content_tag :i, nil, class: 'icon-volume-up cgreen' else content_tag :i, nil, class: 'icon-circle-blank cblue' end end end
class ReviewsController < ApplicationController before_filter :authenticate_user!, except: [:index, :show] def new @movie = Movie.find(params[:movie_id]) @review = Review.new end def create @movie = Movie.find(params[:movie_id]) @review = @movie.reviews.build(review_params) @review.user = current_user if @review.save redirect_to movie_path(@movie) else render action: 'new' end end private def review_params params.require(:review).permit(:body, :rating, :movie_id, :user_id, :vote_count) end end
require 'spec_helper' hiera_file = 'spec/fixtures/hiera/hiera.yaml' # <- required to find hiera configuration file # test our main class (init.pp) describe 'stdmodule', :type => :class do # test without hiera lookup (using class defaults) context 'without hiera data' do it { should contain_class('stdmodule') } # <- check for classes included it { should contain_class('stdmodule').with_myparam('foo') } # <- check for classes with parameters it { should contain_class('stdmodule::basic') } # <- check for subclasses it { should contain_class('stdmodule::package_file_service') } it { should contain_stdmodule__defines('foobar_define') } # <- check for defines end # test with explicit params given on class definition context 'with explicit data' do let(:params) {{ # <- set explizit params :myparam => 'newvalue' }} it { should contain_class('stdmodule').with_myparam('newvalue') } end # test with explicit hiera lookup context 'with explicit hiera lookup' do # set hiera_config let (:hiera_config) { hiera_file } hiera = Hiera.new(:config => hiera_file) # <- use Hiera ruby class variable = hiera.lookup('stdmodule::myparam', nil, nil) # <- do hiera lookup let (:params) {{ :myparam => variable # <- set parameter to hiera lookup }} it { should contain_class('stdmodule').with_myparam(variable) } end end
class AddDefaultToEmailColumnInUsers < ActiveRecord::Migration[5.0] def change change_column :users, :reminder_email_sent, :date, default: 20.years.ago end end
class CardAccount < CardAccount.superclass module Query class AnnualFeeDue def self.call today = Date.current current_year = today.year current_month = today.month Card.accounts.unclosed.where( %[date_part('month', "cards"."opened_on") = #{current_month} AND date_part('year', "cards"."opened_on") <> #{current_year}], ) end end end end
namespace :easyproject do namespace :scheduler do desc <<-END_DESC Example: bundle exec rake easyproject:scheduler:run_tasks RAILS_ENV=production bundle exec rake easyproject:scheduler:run_tasks force=true RAILS_ENV=production END_DESC task :run_tasks => :environment do force = !!ENV.delete('force') EasyRakeTask.execute_scheduled(force) end end end
class Admin < ApplicationRecord before_save { self.email = email.downcase } VALNAME = /[0-9a-z_]{6,12}/i validates :name, presence: true,length: {maximum: 12 }, format: { with: VALNAME } VALEMAIL = /[0-9a-z]*@[0-9a-z]*\.[0-9a-z]*/i validates :email, presence: true, length: { maximum: 256 }, format: { with: VALEMAIL }, uniqueness: { case_sensitive: false } validates :password, presence: true, length: { maximum: 256 } has_secure_password end
FactoryGirl.define do factory :rating do name "arslan" email "user@user.com" overall_review "3" instructor_review "4" job_assistance_review "1" curriculum_review "5" title "this is great" camp_id 1 description "this is one of the best value of my life and we like to attend this session and this is one the best achievement and like is great new famous alive no one is great life attractive salary and this is great achievemnt" end end
class Player < ApplicationRecord validates :name, presence: true validates :last_name, presence: true validates :money, presence:true has_many :bets def probability value = rand() if value <=0.02 return "green" elsif value <=0.51 return "red" else return "black" end end def range value=rand(0.08..0.151) return value.round(2) end end
class Tag < ActiveRecord::Base attr_accessible :merchant_id, :category_id validates :merchant_id, :category_id, presence: true validates :merchant_id, uniqueness: { scope: :category_id } belongs_to :merchant belongs_to :category end
class RemoveTechnicianIdFromInspections < ActiveRecord::Migration def up remove_column :inspections, :technician_id end def down end end
class RequestsController < ApplicationController def create @request = current_user.requests.build(host_id: params[:host_id]) @request.status = 'Pending host acceptance' if @request.save flash[:notice] = 'Request sent.' redirect_to root_url else flash[:notice] = 'Request failed to send.' redirect_to root_url end end def destroy @request = current_user.requests.find(params[:id]) @request.destroy flash[:notice] = 'Request deleted' redirect_to root_path end end
# == Schema Information # # Table name: leafs # # id :integer not null, primary key # content :text # provider_id :integer # image_url :string(255) # time_stamp :datetime # weibo_id :string(255) # created_at :datetime not null # updated_at :datetime not null # video :string(255) # width :integer # height :integer # class Leaf < ActiveRecord::Base belongs_to :provider validates :time_stamp, :uniqueness => {:scope => :provider_id } before_destroy :clean_image after_create :fetch_image IMAGE_URL = "/system/images/leaf/" IMAGE_PATH = "#{Rails.root}/public"+IMAGE_URL def image(style = :large,remote = (Rails.env != "production")) if image_url if remote case style when :thumb if provider.provider == "tumblr" image_url.sub(/_\d+\./,"_100.") else image_url.sub('large','thumbnail') end when :medium if provider.provider == "tumblr" image_url.sub(/_\d+\./,"_400.") else image_url.sub('large','bmiddle') end when :large image_url end else# 本地图片 case style when :large image_url else IMAGE_URL + local_image_name(style) end end end end def local_image_name(style) ext = image_url.split('.')[-1] return "#{self.id}/#{style}.#{ext}" end def clean_image path = IMAGE_PATH + self.id.to_s if Rails.env == "production" and File.exist?(path) `rm -rf #{path}` Leaf.logger.info("INFO #{path} has been destroyed!") end end def fetch_image if Rails.env == "production" and !self.image_url.blank? Grape::LeafImage.new(self).download end end def self.logger Logger.new(File.join(Rails.root,"log","leaf.log")) end # 下载所有图 def self.fetch_all_image(opts={}) Leaf.where("image_url IS NOT NULL").each do |l| if opts[:geo] w,h = Grape::ImageConvert.geo(IMAGE_PATH + l.local_image_name(:medium)) l.update_attributes(:width => w,:height => h) else Grape::LeafImage.new(l).download end end end def as_json(rw = 194) { :id => id, :url => provider.url, :avatar => provider.avatar, :pid => provider.id, :name => provider.user_name, :time_stamp => time_stamp, :content => content, :img => image(:medium), :img_large => image(:large), :height => real_height(rw), :video => video } end private def real_height(real_width) if height (height.to_f/width.to_f)*real_width.to_i end end end
module MLP class Node attr_accessor :threshold, :weights # Takes a threshold_function, which is just an object that # responds to #call and takes and returns a float. # an array of weights with one for each input, # and an optional threshold. def initialize(threshold_function, weights) @threshold_function = threshold_function @weights = weights end def get_output(input) @input = input @net = 0.0 @weights.each_with_index do |weight, i| @net += weight * input[i] end return @threshold_function.call @net end end end
# frozen_string_literal: true require 'pry' class TicTacToe def initialize @board = Array.new(9, ' ') end WIN_COMBINATIONS = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [6, 4, 2] ].freeze def display_board puts " #{@board[0]} | #{@board[1]} | #{@board[2]} " puts '-----------' puts " #{@board[3]} | #{@board[4]} | #{@board[5]} " puts '-----------' puts " #{@board[6]} | #{@board[7]} | #{@board[8]} " end def input_to_index(move) move = move.to_i move -= 1 end def move(move, token = 'X') @board[move] = token end def position_taken?(move) @board[move] != ' ' end def valid_move?(index) if (0..8).include?(index) !position_taken?(index) else false end end def turn_count count = @board.count { |num| num == 'X' || num == 'O' } count end def current_player current_player = (turn_count % 2).zero? ? 'X' : 'O' @winning_player = (turn_count % 2).zero? ? 'O' : 'X' current_player end def turn print 'Choose a position(1-9):' choice = gets.chomp move_index = input_to_index(choice) player = current_player if valid_move?(move_index) move(move_index, player) display_board else turn end end def won? x_winner = nil o_winner = nil WIN_COMBINATIONS.each do |winners| x_winner = winners if winners.all? { |index| @board[index] == 'X' } end WIN_COMBINATIONS.each do |winners| o_winner = winners if winners.all? { |index| @board[index] == 'O' } end x_winner || o_winner end def full? @board.all? { |i| i != ' ' } end def draw? if full? false if won? end if full? true if !won? end end def over? if won? true else draw? end end def winner if won? current_player @winning_player end end def play until over? turn end if draw? puts "Cat's Game!" else winner puts "Congratulations #{@winning_player}!" end end end # The mostly elegent method # def won? # WIN_COMBINATIONS.any? do |combo| # if position_taken?(combo[0]) && @board[combo[0]] == @board[combo[1]] && @board[combo[1]] == @board[combo[2]] # return combo # end # end # end
require 'spec_helper' describe WorkRequest do before(:each) do @attr = { :name => "Example Name", :email => "edcervenka@yahoo.com", :job_title => "Example job title", :composer_name => "Example composer name", :work_name => "Example work name", :date => "Example date" } end it "should create a new instance given valid attributes" do WorkRequest.create!(@attr) end it "should require a name" do no_name_work_request = WorkRequest.new(@attr.merge(:name => "")) no_name_work_request.should_not be_valid end it "should require an email address" do no_email_work_request = WorkRequest.new(@attr.merge(:email => "")) no_email_work_request.should_not be_valid end it "should require a job title" do no_job_title_work_request = WorkRequest.new(@attr.merge(:job_title => "")) no_job_title_work_request.should_not be_valid end it "should require a composer name" do no_composer_name_work_request = WorkRequest.new(@attr.merge(:composer_name => "")) no_composer_name_work_request.should_not be_valid end it "should require a work name" do no_work_name_work_request = WorkRequest.new(@attr.merge(:work_name => "")) no_work_name_work_request.should_not be_valid end it "should require a date" do no_date_work_request = WorkRequest.new(@attr.merge(:date => "")) no_date_work_request.should_not be_valid end it "should accept valid email addresses" do addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp] addresses.each do |address| valid_email_user = WorkRequest.new(@attr.merge(:email => address)) valid_email_user.should be_valid end end it "should reject invalid email addresses" do addresses = %w[user@foo,com user_at_foo.org example.user@foo.] addresses.each do |address| invalid_email_user = WorkRequest.new(@attr.merge(:email => address)) invalid_email_user.should_not be_valid end end end
require File.dirname(__FILE__) + '/../spec_helper' describe ADCK::Message do context "message is too long" do let(:message) {'hello ' *100} it "should truncate with dots default" do msg = ADCK::Message.new(body: message, truncate: true) json = msg.package MultiJson.load(json)['aps']['alert']['body'][-3,3].should == '...' end it "should truncate with defined value" do msg = ADCK::Message.new(body: message, truncate: '[end]') json = msg.package MultiJson.load(json)['aps']['alert']['body'][-5,5].should == '[end]' end it "should raise error" do msg = ADCK::Message.new(body: message) expect {msg.package}.to raise_error(ADCK::Message::PayloadTooLarge) end end end
class Report < ApplicationRecord belongs_to :reporter, class_name: User.name belongs_to :reported, polymorphic: true end
require 'weapon' class BattleBot @@count = 0 attr_reader :name, :health, :enemies, :weapon def initialize(name) @name = name @health = 100 @enemies = [] @weapon = nil @dead = false @@count += 1 end def self.count @@count end def pick_up (new_weapon) raise ArgumentError unless new_weapon.is_a? Weapon raise ArgumentError if new_weapon.bot.is_a? BattleBot if @weapon == nil @weapon = new_weapon new_weapon.bot = self new_weapon else nil end end def drop_weapon @weapon.bot = nil @weapon = nil end def take_damage( damage ) raise ArgumentError unless damage.is_a? Fixnum if ! @dead @health = [ @health - damage, 0 ].max if @health == 0 @dead = true @@count -= 1 end end @health end def heal if ! @dead @health = [ @health + 10, 100 ].min end @health end def attack (victim_bot) raise ArgumentError unless victim_bot.is_a? BattleBot raise ArgumentError if victim_bot == self raise ArgumentError if weapon == nil victim_bot.receive_attack_from( self ) end def receive_attack_from (enemy_bot) raise ArgumentError unless enemy_bot.is_a? BattleBot raise ArgumentError if enemy_bot == self raise ArgumentError if enemy_bot.weapon == nil take_damage( enemy_bot.weapon.damage ) if !( @enemies.include? enemy_bot ) @enemies << enemy_bot end defend_against(enemy_bot) end def defend_against( enemy_bot ) if !dead? && has_weapon? attack(enemy_bot) end end def has_weapon? weapon != nil end def dead? @dead end private def health= (s) @health = s end end
class Discussion < ActiveRecord::Base belongs_to :Post validates :content, presence: true, length: { minimum: 1, maximum: 200, tokenizer: lambda { |str| str.split(/\s+/) }, too_short: "must have at least %{count} words", too_long: "must have at most %{count} words" }; end
class CreateEventDictionaryEventTags < ActiveRecord::Migration def change create_table :event_dictionary_event_tags do |t| t.integer :event_dictionary_id t.integer :event_tag_id t.timestamps end end end
require_relative('../db/sql_runner') # require('pry') class Member attr_reader :id attr_accessor :first_name, :last_name, :membership_type def initialize(options) @id = options['id'].to_i if options['id'] @first_name = options['first_name'] @last_name = options['last_name'] @membership_type = options['membership_type'] end def save() sql = "INSERT INTO members(first_name, last_name, membership_type) VALUES ($1, $2, $3) RETURNING id" values = [@first_name, @last_name, @membership_type] results = SqlRunner.run(sql, values) @id = results.first()['id'].to_i end def self.all() sql = "SELECT * FROM members" results = SqlRunner.run(sql) return results.map{|member| Member.new(member)} end def self.find(id) sql = "SELECT * FROM members WHERE id = $1" values = [id] member = SqlRunner.run(sql, values) results = Member.new(member.first) return results end def update() sql = "UPDATE members SET(first_name, last_name, membership_type) = ($1, $2, $3) WHERE id = $4" values = [@first_name, @last_name, @membership_type, @id] SqlRunner.run(sql, values) end def self.delete_all() sql = "DELETE FROM members" SqlRunner.run(sql) end def self.delete(id) sql = "DELETE FROM members WHERE id = $1" values = [id] SqlRunner.run(sql, values) end def booked_classes() sql = "SELECT members.* FROM members INNER JOIN bookings ON bookings.member_id = members.id INNER JOIN gym_classes ON bookins.gym_class_id = gym_classes.id WHERE members.id = $1" values = [@id] results = SqlRunner.run(sql, values) return results.map { |gym_class|GymClass.new(gym_class)} end end # binding.pry # nil
class HourlyData def initialize(data) @data = data end def decorate @data.map do |hash| time = DateTime.parse(hash['DATE_TIME']) if in_range(time) build(hash) end end.compact end private def highlight(uv) uv.to_i > 5 ? 'red' : 'default' end def in_range(time) floor = DateTime.now.utc.change({ hour: 9 }) ceiling = DateTime.now.utc.change({ hour: 21 }) time.between?(floor, ceiling) end def build(hash) { hour: DateTime.parse(hash['DATE_TIME']).strftime('%-I %P'), order: hash['ORDER'], uv_index: hash['UV_VALUE'], class: highlight(hash['UV_VALUE']) } end end
class MenusController < ApplicationController def index end def show # redirect back to index if meal is not specified unless params[:meal].nil? @meal = Meal.where(name: params[:meal].downcase).first # redirect back to index if meal is not found if @meal.blank? flash[:warning] = "#{params[:meal].humanize} Menu does not exist." redirect_to menus_path end # retrieve the list of all items associated with meal # order the rows # eager load all the data from the associated tables @menu = Menu.where(meal: @meal) .order(:meal_id, :category_id, :item_id, :size_id, :meat_id) .includes(:meal, :category , :item , :size , :meat ) @menu_h = {} @menu.each do |row| category = row.category.name item = row.item.name @menu_h[category] = {} unless @menu_h.has_key?(category) category_h = @menu_h[category] category_h[item] = {} unless category_h.has_key?(item) item_h = category_h[row.item.name] item_h[:description] = row.item.description item_h[:price] = row.item.price item_h[:sizes] = [] unless item_h.has_key?(:sizes) item_h[:meats] = {} unless item_h.has_key?(:meats) item_h[:sizes].push(row.size.name) if row.size item_h[:meats][row.meat.name] = row.meat.price if row.meat end else flash[:warning] = "Please choose a menu." redirect_to menus_path end end end
class AddIndexToStaffStaffId < ActiveRecord::Migration[5.0] def change add_index :staffs, :staff_id, unique: true end end
require 'nokogiri' require 'open-uri' require 'fileutils' require_relative 'zip' # this is a shortcut if you have not configured OpenSSL on windows machines. # For more information, see: https://gist.github.com/fnichol/867550 # require 'openssl' # OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE class MangaScraper def initialize(url) @page = Nokogiri::HTML(open(url)) @title = @page.css('h3').text @link = @page.css('a[title=Read]').attr('href').value + "page/" end def create_temp_folder begin Dir.mkdir(@title) rescue puts "Folder already exists!" end end def download_image(link) encoded_url = URI::encode(link.value) #this protects the scraper from invalid queries such as spaces in a url download = open(encoded_url) IO.copy_stream(download, "#{@title}/#{download.base_uri.to_s.split('/')[-1]}") end def zip_files puts "Zipping files..." ZipFileGenerator.new(@title, "#{@title}.zip").write() puts "Zipping Complete! Cleaning up temporary files..." FileUtils.rm_rf(@title) puts "Done!" end def run create_temp_folder page_number = 1 loop do begin current_page = @link + page_number.to_s page = Nokogiri::HTML(open(current_page)) image_source = page.css('img').attr('src') puts "Downloading #{current_page}..." download_image(image_source) page_number += 1 rescue puts "Download Complete!" break end end zip_files end end def request_url puts "Please enter the URL (or type 'exit' to quit):" url = gets.chomp return if url == "exit" begin scraper = MangaScraper.new(url) scraper.run rescue puts "Invalid URL!" end request_url end request_url
Class Language def initialize(name, creator) @name = name @creator = creator end def description puts "I'm ${@name} and I was created by #{@creator}!" end end class Circle pi = 3.14159 radius = 0.0 def Circle(r) radius = r end def setRadius(r) radius = r end def getRadius() return radius end def getArea() return pi * radius * radius; end def getCircmference() return 2 * pi * radius end a = Circle.new(10.0) puts "Area is " + a.getArea() puts "Diameter is " + a.getRadius() puts "Circumference is " + a.getCircmference() end
class AddColumnsToImport < ActiveRecord::Migration def self.up add_column :imports, :messages, :text add_column :imports, :started_at, :datetime add_column :imports, :ended_at, :datetime add_column :imports, :records, :integer end def self.down remove_column :imports, :records remove_column :imports, :ended_at remove_column :imports, :started_at remove_column :imports, :messages end end
# == Schema Information # # Table name: messages # # id :integer not null, primary key # body :text # created_at :datetime not null # updated_at :datetime not null # letter_conversation_id :integer # user_id :integer # # Indexes # # index_messages_on_letter_conversation_id (letter_conversation_id) # index_messages_on_user_id (user_id) # class Message < ActiveRecord::Base belongs_to :letter_conversation belongs_to :user validates_presence_of :body, :letter_conversation_id, :user_id end
require "set" class String def integer? Integer(self) != nil rescue false end end #---------------Union Method------------------------------------------ puts p "Union Method" print "Number of values to enter: " count = gets.chomp while !(count.integer?) print "Number of values to enter: " count = gets.chomp end count = count.to_i arr = [] for i in 1..count arr.push(gets.chomp) end #arr2 = arr.select{|x| arr.count(x)>1} #p (arr2) #arr.select! {|x| arr.count(x)==1} #p (arr) print "Unique array is " p (arr | []) puts puts =begin #---------------Check Uniqueness before insertion----------------- p "Check uniqueness before insertion method" print "Number of values to enter: " count = gets.chomp while !(count.integer?) print "Number of values to enter: " count = gets.chomp end count = count.to_i arr = [] for i in 1..count inp=gets.chomp if(!arr.include?(inp)) arr.push(inp) end end print "Unique array is " p arr puts puts #---------------Set Method--------------------------------- p "Set Method" print "Number of values to enter: " count = gets.chomp while !(count.integer?) print "Number of values to enter: " count = gets.chomp end count = count.to_i arr = [] for i in 1..count arr.push(gets.chomp) end set1 = arr.to_set arr = set1.to_a print "Unique array is " p arr =end
ActiveAdmin.register NormalUser do index do selectable_column column :email column :name column :provider column :sign_in_count column :created_at column :updated_at column :internal_user, label: 'Is his User an TouriMe internal User?' actions end permit_params :email, :password, :password_confirmation,:internal_user form do |f| f.inputs "User Details" do f.input :email f.input :internal_user, label: 'Mark this user as an TouriMe internal user' end f.actions end end
require 'securerandom' module Rockauth class ClientGenerator < Rails::Generators::NamedBase source_root File.expand_path('../../templates', __FILE__) desc "Generate a rockauth client" class_option :environment, default: 'production', desc: 'Environment for the client' def generate_client client_id = SecureRandom.urlsafe_base64(16) client_secret = SecureRandom.urlsafe_base64(32) file_path = Rails.root.join("config/rockauth_clients.yml") environments = {} if File.exists?(file_path) environments = YAML.load_file(file_path) end environments[options[:environment]] ||= [] environments[options[:environment]] << { 'client_id' => client_id, 'client_title' => name, 'client_secret' => client_secret } File.open(file_path, 'wb') do |file| file.write environments.stringify_keys.to_yaml(cannonical: false).gsub(/\A---\n/, '') end end end end
require 'fastlane/action' require_relative '../helper/ios_flavors_helper' module Fastlane module Actions module SharedValues IOS_FLAVORS_APP_INPUT = :IOS_FLAVORS_APP_INPUT IOS_FLAVORS_APP_OUTPUT = :IOS_FLAVORS_APP_OUTPUT end class CreateSimFlavorsAction < Action def self.run(params) Helper::IOSFlavorsHelper.verify_dependencies params = parse_params(params) create_flavors_from(app: params[:app], target_plist: params[:target_plist]) end def self.description "Create multiple build flavors of an iOS .app (for the simulator) using a directory of .plist files" end def self.authors ["Zachary Davison"] end def self.output [ ['IOS_FLAVORS_APP_INPUT', 'The input .app file'], ['IOS_FLAVORS_APP_OUTPUT', 'The output directory containing flavors'] ] end def self.available_options [ FastlaneCore::ConfigItem.new(key: :app, env_name: "IOS_FLAVORS_APP", description: "The .app file to use as a basis for creating your flavors", optional: false, type: String), FastlaneCore::ConfigItem.new(key: :flavors, env_name: "IOS_FLAVORS_DIRECTORY", description: "The directory containing .plist files to use to create your flavors", default_value: "fastlane/flavors", optional: true, type: String), FastlaneCore::ConfigItem.new(key: :output_directory, env_name: "IOS_FLAVORS_OUTPUT", description: "The output flavors directory", default_value: "fastlane/build_output/flavors", optional: true, type: String), FastlaneCore::ConfigItem.new(key: :target_plist, env_name: "IOS_FLAVORS_TARGET_PLIST", description: "The name of the .plist file to overwrite with your flavor .plist", default_value: "Info.plist", optional: true, type: String) ] end def self.is_supported?(platform) [:ios].include?(platform) end def self.parse_params(params) app = params[:app] flavors = params[:flavors] || 'flavors' output_directory = params[:output_directory] || 'build_output/flavors' target_plist = params[:target_plist] || 'Info.plist' raise "You must supply an :app." unless app raise 'You must supply a :flavors directory of .plist files.' unless flavors raise 'You must supply a :target_plist to be replaced in the :app.' unless target_plist raise "#{app} not found." unless Dir.exist?(app) raise "#{flavors} not found." unless Dir.exist?(flavors) lane_context[SharedValues::IOS_FLAVORS_APP_INPUT] = File.expand_path(flavors) lane_context[SharedValues::IOS_FLAVORS_APP_OUTPUT] = File.expand_path(output_directory) return { app: File.expand_path(app), flavors: flavors, target_plist: target_plist } end def self.create_flavors_from(app:, target_plist:) input_directory = Actions.lane_context[SharedValues::IOS_FLAVORS_APP_INPUT] output_directory = Actions.lane_context[SharedValues::IOS_FLAVORS_APP_OUTPUT] FileUtils.mkdir_p(output_directory) Dir["#{input_directory}/*.plist"].each do |flavor| self.create_flavor_app(app: app, plist: flavor, target_plist: target_plist) end end def self.create_flavor_app(app:, plist:, target_plist:) output_directory = Actions.lane_context[SharedValues::IOS_FLAVORS_APP_OUTPUT] expanded = { plist: File.expand_path(plist) } output_filename = File.basename(plist, '.plist') output_app = "#{output_directory}/#{output_filename}.app" UI.header "Flavor: #{output_filename}" UI.message "Copying #{app} to #{output_app}" FileUtils.cp_r(app, output_app, remove_destination: true) UI.message "Replacing #{output_app}/#{target_plist} with #{plist}" FileUtils.cp_r(expanded[:plist],"#{output_app}/#{target_plist}", remove_destination: true) end end end end
require 'rails_helper' RSpec.describe TokensController do describe "POST create" do context 'when params is correct' do it "creates user token" do create(:user, id: 1, username: 'ximbinha', password: '12345678') params = {"username": "ximbinha", "password": "12345678"} post :create, params: params expect(JSON.parse(response.body).has_key?("token")).to eq(true) expect(response.status).to eq(201) end end context 'when user not exist' do it "does return unauthorized" do params = {"username": "user2ddd", "password": "2345678"} post :create, params: params expect(response.body).to be_empty expect(response.status).to eq(401) end end context 'when params is invalid' do it "does return unauthorized" do params = {"usernames": "user2", "passwords": "12345678"} post :create, params: params expect(response.body).to be_empty expect(response.status).to eq(401) end end end end
require 'spec_helper' describe Book do before do @valid_attributes = { :title => "Oliver Twist", :description => "A book about an orphan", :year => 1838 } end it "should be valid with valid attributes" do book = Book.new(@valid_attributes) book.should be_valid end it "should have a title" do @invalid_attributes = @valid_attributes.clone @invalid_attributes.delete(:title) Book.new(@invalid_attributes).should_not be_valid end it "should have description as empty string by default" do @valid_attributes.delete(:description) book = Book.create!(@valid_attributes) book.description.should == "" end it "should have a year as a number" do book = Book.new(@valid_attributes) book.year = "foo" book.should_not be_valid end end
class SnippetTag < ActiveRecord::Base belongs_to :snippet belongs_to :tag end
require 'rack/rewrite' require 'spree/core' module Refinery module Stores class Engine < Rails::Engine include Refinery::Engine isolate_namespace Refinery::Stores engine_name :refinery_stores initializer "register refinerycms_stores plugin" do Refinery::Plugin.register do |plugin| plugin.name = "refinerycms_stores" plugin.url = proc { Spree::Core::Engine.routes.url_helpers.admin_path } plugin.pathname = root plugin.menu_match = /store\/admin\/?(products|orders)?/ plugin.activity = { :class_name => :'spree/product' } end end def self.activate # Dir.glob(File.join(File.dirname(__FILE__), "../../../app/**/*_decorator*.rb")) do |c| # Rails.configuration.cache_classes ? require(c) : load(c) # end ::ApplicationController.send :include, Spree::AuthenticationHelpers ::ApplicationController.send :include, Refinery::AuthenticatedSystem end config.after_initialize do Refinery.register_extension(Refinery::Stores) Refinery::Stores::Override.enable end config.to_prepare &method(:activate).to_proc config.middleware.insert_before(Rack::Lock, Rack::Rewrite) do rewrite %r{/refinery/store/(\w+)}, "/store/admin/$1" end end end end
FactoryGirl.define do factory :order do channel_id { ENV['SELECTED_CHANNELS'].split(',').sample.to_i } price_in_dollars { rand(0.0...10.0).round(2) } placement_date { FFaker::Time.date } legacy_id { rand(0...100) } end end
json.array!(@user_rankings) do |user_ranking| json.extract! user_ranking, :id, :user_id, :path, :points json.url user_ranking_url(user_ranking, format: :json) end
#### # # Chargeable # # Holds information to turn a charge into a debit # # Invoicing needs to generate debits from charges. # It calls on account for due charges and in turn charge # generates a Chargeable describing a charge that is due # in the queried date range. # # Hashes use symbols as hash keys - faster and saves memory. # http://stackoverflow.com/questions/8189416/why-use-symbols-as-hash-keys-in-ruby # #### # class Chargeable include Equalizer.new(:account_id, :charge_id, :at_time, :amount) attr_reader :account_id, :charge_id, :at_time, :period, :amount def self.from_charge(account_id:, charge_id:, at_time:, period:, amount:) new account_id: account_id, charge_id: charge_id, at_time: at_time, period: period, amount: amount end # instance_values is a rails object that returns instances # as hashes with keys as named strings . # def to_hash **overrides instance_values.symbolize_keys.merge overrides end private def initialize(account_id:, charge_id:, at_time:, period:, amount:) @account_id = account_id @charge_id = charge_id @at_time = at_time @period = period @amount = amount end end
require_relative '../spec_helper' describe "Session" do describe "login" do before :all do User.destroy_all @user = FactoryGirl.create(:user) @user.save end it "should redirect to first level upon successful login" do visit '/login' fill_in 'email', :with => @user.email fill_in 'Password', :with => @user.password click_button 'Login' expect(current_path).to eq("/levels/1") end it "should flash an error if email or password is incorrect" do visit '/login' fill_in 'email', :with => "gargdfsdfsadf" fill_in 'Password', :with => @user.password click_button 'Login' expect(page).to have_content("Email or password is incorrect") end end describe "header changes depending on login" do before :each do User.destroy_all @user = FactoryGirl.create(:user) @user.save end it "should show the sign up and login links when a user is logged out" do visit '/' expect(page).to have_content("Login") expect(page).to have_content("Sign Up") expect(page).to have_no_content("Logout") end it "should show to logout link when a user is logged in" do visit '/' visit '/login' fill_in 'email', :with => @user.email fill_in 'Password', :with => @user.password click_button 'Login' expect(page).to have_content("Logout") expect(page).to have_no_content("Login") expect(page).to have_no_content("Sign Up") end end describe "creating a new account" do before :each do User.destroy_all @user = FactoryGirl.build(:user) end it "should log you in if you make a new account" do visit '/users/new' fill_in 'Username', :with => @user.user_name fill_in 'user_email', :with => @user.email fill_in 'Password', :with => @user.password fill_in 'user_password_confirmation', :with => @user.password click_button 'Create User' new_user = User.find_by(:email => @user.email) expect(current_path).to eq("/levels/1") end it "should tell you if a username is already taken" do @user.save visit '/users/new' fill_in 'Username', :with => @user.user_name fill_in 'user_email', :with => @user.email fill_in 'Password', :with => @user.password fill_in 'user_password_confirmation', :with => @user.password click_button 'Create User' expect(page).to have_content("User name has already been taken") end it "should redirect you to the homepage if you're logged in" do @user.save visit '/login' fill_in 'email', :with => @user.email fill_in 'Password', :with => @user.password click_button 'Login' visit '/users/new' expect(current_path).to eq("/") end it "should tell you if your password doesn't match the confirmation" do visit '/users/new' fill_in 'Username', :with => @user.user_name fill_in 'user_email', :with => @user.email fill_in 'Password', :with => @user.password fill_in 'user_password_confirmation', :with => "lolllll" click_button 'Create User' expect(page).to have_content("Password confirmation doesn't match Password") end it "should tell you if your email has already been used" do visit '/users/new' fill_in 'Username', :with => @user.user_name fill_in 'user_email', :with => @user.email fill_in 'Password', :with => @user.password fill_in 'user_password_confirmation', :with => @user.password click_button 'Create User' click_link('Logout') visit '/users/new' fill_in 'Username', :with => @user.user_name fill_in 'user_email', :with => @user.email fill_in 'Password', :with => @user.password fill_in 'user_password_confirmation', :with => @user.password click_button 'Create User' expect(page).to have_content("Email has already been taken") expect(page).to have_content("User name has already been taken") end end end
require 'spec_helper' describe UserGroup do #let(:user) { FactoryGirl.create(:user) } #let(:group) { FactoryGirl.create(:user_group) } before do #@user_group = user.user_groups.build() @user_group = FactoryGirl.create(:user_group) end #before { @user_group = user.user_groups.build(name: "MIT") } subject { @user_group } it { should respond_to(:name) } it { should be_valid } describe "with blank name" do before { @user_group.name = " " } it { should_not be_valid } end describe "with name that is too long" do before { @user_group.name = "a" * 41 } it { should_not be_valid } end describe "accessible attributes" do it "should not allow access to user_id" do expect do UserGroup.new(user_id: 1) end.should raise_error(ActiveModel::MassAssignmentSecurity::Error) end end end
require 'rake/testtask' require 'rake/extensiontask' require 'bundler/gem_tasks' Rake::ExtensionTask.new('byebug') do |ext| ext.lib_dir = 'lib/byebug' end # Override default rake tests loader class Rake::TestTask def rake_loader 'test/test_helper.rb' end end desc "Run MiniTest suite" task :test do Rake::TestTask.new do |t| t.verbose = true t.warning = true t.pattern = 'test/*_test.rb' end end base_spec = eval(File.read('byebug.gemspec'), binding, 'byebug.gemspec') task :default => :test desc 'Run a test in looped mode so that you can look for memory leaks' task 'test_loop' do code = %Q[loop{ require '#{$*[1]}' }] cmd = %Q[ruby -Itest -e "#{ code }"] system cmd end desc 'Watch memory use of a looping test' task 'test_loop_mem' do system "watch \"ps aux | grep -v 'sh -c r' | grep [I]test\"" end
require "cinch" require "sequel" class Karma include Cinch::Plugin listen_to :add_karma def initialize(*) super @DB = Sequel.sqlite(File.dirname(__FILE__)+"/../rubee.db") end def renderKarma(nick) nicks = @DB[:karma] n = nicks.where(:nick => nick.capitalize).first return "Karma for " + n[:nick] + " = " + n[:karma].to_s end def addNick(nick) nicks = @DB[:karma] nicks.insert(:nick => nick.capitalize, :karma => 0) end def nickExists(nick) nicks = @DB[:karma] n = nicks.where(:nick => nick.capitalize).first if n return true else return false end end match(/^\karma (\w+)$/i, method: :getKarma, use_prefix: false) def getKarma(m, nick) unless nickExists(nick) addNick(nick) end m.reply renderKarma(nick) end match(/^\+\s(\w+)$/i, method: :addKarma, use_prefix: false) def addKarma(m, nick) nicks = @DB[:karma] if m.user.to_s.capitalize == nick.capitalize return false end unless nickExists(nick) addNick(nick) end n = nicks.where(:nick => nick.capitalize).first k = n[:karma] + 1 nicks.where(:nick => nick.capitalize).update(:karma => k) m.reply renderKarma(nick) end end
require 'rails_helper' RSpec.describe User, type: :model do let(:user) { User.create( name: "Luffy", email: "luffy@onepiece.com", password: "password" ) } let(:admin) { User.create( name: "Nami", email: "admin@manga.com", password: "password", admin: true ) } let(:oda) { Author.create(name: "Oda, Eiichiro") } let(:watsuki) { Author.create(name: "Watsuki, Nobuhiro") } let(:onepiece) { Manga.create( title: "One Piece", status: "On Going", author_id: oda.id, start_date: 19970722 ) } let(:kenshin) { Manga.create( title: "Rurouni Kenshin", status: "Finished", volumes: 28, chapters: 259, author_id: watsuki.id, start_date: 19940412, end_date: 19990921 ) } it "is valid with a name, email, and password" do expect(user).to be_valid end it "is not valid without a password" do expect(User.new(name: "Name")).not_to be_valid end it "is valid with an admin boolean" do expect(admin).to be_valid end it "defaults to admin => false" do expect(user.admin).to eq(false) end it "has many collections" do first_collection = Collection.create(:user_id => user.id, :manga_id => kenshin.id) second_collection = Collection.create(:user_id => user.id, :manga_id => onepiece.id) expect(user.collections.first).to eq(first_collection) expect(user.collections.last).to eq(second_collection) end it "has many manga through collections" do user.mangas << [kenshin, onepiece] expect(user.mangas.first).to eq(kenshin) expect(user.mangas.last).to eq(onepiece) end end
class AddDatesToEvents < ActiveRecord::Migration def change add_column :events, :sign_up_start, :datetime add_column :events, :sign_up_end, :datetime add_column :events, :event_end, :datetime end end
require 'spec_helper' describe 'vault' do let :node do 'agent.example.com' end on_supported_os.each do |os, facts| context "on #{os} " do let :facts do facts.merge(service_provider: 'init', processorcount: 3) end context 'vault class with simple configuration' do let(:params) do { storage: { 'file' => { 'path' => '/data/vault' } }, listener: { 'tcp' => { 'address' => '127.0.0.1:8200', 'tls_disable' => 1 } } } end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('vault') } it { is_expected.to contain_class('vault::params') } it { is_expected.to contain_class('vault::install').that_comes_before('Class[vault::config]') } it { is_expected.to contain_class('vault::config') } it { is_expected.to contain_class('vault::service').that_subscribes_to('Class[vault::config]') } it { is_expected.to contain_service('vault'). with_ensure('running'). with_enable(true) } it { is_expected.to contain_user('vault') } it { is_expected.to contain_group('vault') } it { is_expected.not_to contain_file('/data/vault') } context 'do not manage user and group' do let(:params) do { manage_user: false, manage_group: false } end it { is_expected.not_to contain_user('vault') } it { is_expected.not_to contain_group('vault') } end it { is_expected.to contain_file('/etc/vault'). with_ensure('directory'). with_purge('true'). with_recurse('true'). with_owner('vault'). with_group('vault') } it { is_expected.to contain_file('/etc/vault/config.json'). with_owner('vault'). with_group('vault'). with_content(%r|"storage":\s*{\s*"file":\s*{\s*"path":\s*"\/data\/vault"|). with_content(%r|"listener":\s*{"tcp":\s*{"address":\s*"127.0.0.1:8200"|). with_content(%r{"address":\s*"127.0.0.1:8200"}). with_content(%r{"tls_disable":\s*1}) } it { is_expected.to contain_file('/usr/local/bin/vault').with_mode('0755') } it { is_expected.to contain_exec('setcap cap_ipc_lock=+ep /usr/local/bin/vault'). with_unless('getcap /usr/local/bin/vault | grep cap_ipc_lock+ep'). that_subscribes_to('File[/usr/local/bin/vault]') } context 'disable mlock' do let(:params) do { disable_mlock: true } end it { is_expected.not_to contain_exec('setcap cap_ipc_lock=+ep /usr/local/bin/vault') } it { is_expected.to contain_file('/etc/vault/config.json'). with_content(%r{"disable_mlock":\s*true}) } end context 'default download options' do let(:params) { { version: '0.7.0' } } it { is_expected.to contain_archive('/tmp/vault.zip'). with_source('https://releases.hashicorp.com/vault/0.7.0/vault_0.7.0_linux_amd64.zip'). that_comes_before('File[/usr/local/bin/vault]') } end context 'specifying a custom download params' do let(:params) do { version: '0.6.0', download_url_base: 'http://my_site.example.com/vault/', package_name: 'vaultbinary', download_extension: 'tar.gz' } end it { is_expected.to contain_archive('/tmp/vault.zip'). with_source('http://my_site.example.com/vault/0.6.0/vaultbinary_0.6.0_linux_amd64.tar.gz'). that_comes_before('File[/usr/local/bin/vault]') } end context 'installs from download url' do let(:params) do { download_url: 'http://example.com/vault.zip', install_method: 'archive' } end it { is_expected.to contain_archive('/tmp/vault.zip'). with_source('http://example.com/vault.zip'). that_comes_before('File[/usr/local/bin/vault]') } end context 'installs from repository' do let(:params) do { install_method: 'repo', package_name: 'vault', package_ensure: 'installed' } end it { is_expected.to contain_package('vault') } end end context 'when specifying an array of listeners' do let(:params) do { listener: [ { 'tcp' => { 'address' => '127.0.0.1:8200' } }, { 'tcp' => { 'address' => '0.0.0.0:8200' } } ] } end it { is_expected.to contain_file('/etc/vault/config.json'). with_content(%r{"listener":\s*\[.*\]}). with_content(%r|"tcp":\s*{"address":\s*"127.0.0.1:8200"|). with_content(%r|"tcp":\s*{"address":\s*"0.0.0.0:8200"|) } end context 'when specifying manage_service' do let(:params) do { manage_service: false, storage: { 'file' => { 'path' => '/data/vault' } } } end it { is_expected.not_to contain_service('vault'). with_ensure('running'). with_enable(true) } end context 'when specifying manage_storage_dir' do let(:params) do { manage_storage_dir: true, storage: { 'file' => { 'path' => '/data/vault' } } } end it { is_expected.to contain_file('/data/vault'). with_ensure('directory'). with_owner('vault'). with_group('vault') } end case facts[:os]['family'] when 'RedHat' case facts[:os]['release']['major'].to_i when 2017 context 'RedHat 7 Amazon Linux specific' do let facts do facts.merge(service_provider: 'sysv', processorcount: 3) end context 'includes SysV init script' do it { is_expected.to contain_file('/etc/init.d/vault'). with_mode('0755'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^#!/bin/sh}). with_content(%r{export GOMAXPROCS=\${GOMAXPROCS:-3}}). with_content(%r{OPTIONS=\$OPTIONS:-""}). with_content(%r{exec="/usr/local/bin/vault"}). with_content(%r{conffile="/etc/vault/config.json"}). with_content(%r{chown vault \$logfile \$pidfile}) } end context 'service with non-default options' do let(:params) do { bin_dir: '/opt/bin', config_dir: '/opt/etc/vault', service_options: '-log-level=info', user: 'root', group: 'admin', num_procs: '5' } end it { is_expected.to contain_file('/etc/init.d/vault'). with_mode('0755'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^#!/bin/sh}). with_content(%r{export GOMAXPROCS=\${GOMAXPROCS:-5}}). with_content(%r{OPTIONS=\$OPTIONS:-"-log-level=info"}). with_content(%r{exec="/opt/bin/vault"}). with_content(%r{conffile="/opt/etc/vault/config.json"}). with_content(%r{chown root \$logfile \$pidfile}) } end context 'does not include systemd magic' do it { is_expected.not_to contain_class('systemd') } end context 'install through repo with default service management' do let(:params) do { install_method: 'repo', manage_service_file: :undef } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through repo without service management' do let(:params) do { install_method: 'repo', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through repo with service management' do let(:params) do { install_method: 'repo', manage_service_file: true } end it { is_expected.to contain_file('/etc/init.d/vault') } end context 'install through archive with default service management' do let(:params) do { install_method: 'archive', manage_service_file: :undef } end it { is_expected.to contain_file('/etc/init.d/vault') } end context 'install through archive without service management' do let(:params) do { install_method: 'archive', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through archive with service management' do let(:params) do { install_method: 'archive', manage_service_file: true } end it { is_expected.to contain_file('/etc/init.d/vault') } end end when 6 context 'RedHat 6 specific' do let :facts do facts.merged(service_provider: 'sysv', processorcount: 3) end context 'includes SysV init script' do it { is_expected.to contain_file('/etc/init.d/vault'). with_mode('0755'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^#!/bin/sh}). with_content(%r{export GOMAXPROCS=\${GOMAXPROCS:-3}}). with_content(%r{OPTIONS=\$OPTIONS:-""}). with_content(%r{exec="/usr/local/bin/vault"}). with_content(%r{conffile="/etc/vault/config.json"}). with_content(%r{chown vault \$logfile \$pidfile}) } end context 'service with non-default options' do let(:params) do { bin_dir: '/opt/bin', config_dir: '/opt/etc/vault', service_options: '-log-level=info', user: 'root', group: 'admin', num_procs: '5' } end it { is_expected.to contain_file('/etc/init.d/vault'). with_mode('0755'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^#!/bin/sh}). with_content(%r{export GOMAXPROCS=\${GOMAXPROCS:-5}}). with_content(%r{OPTIONS=\$OPTIONS:-"-log-level=info"}). with_content(%r{exec="/opt/bin/vault"}). with_content(%r{conffile="/opt/etc/vault/config.json"}). with_content(%r{chown root \$logfile \$pidfile}) } end context 'does not include systemd magic' do it { is_expected.not_to contain_class('systemd') } end context 'install through repo with default service management' do let(:params) do { install_method: 'repo', manage_service_file: :undef } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through repo without service management' do let(:params) do { install_method: 'repo', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through repo with service management' do let(:params) do { install_method: 'repo', manage_service_file: true } end it { is_expected.to contain_file('/etc/init.d/vault') } end context 'install through archive with default service management' do let(:params) do { install_method: 'archive', manage_service_file: :undef } end it { is_expected.to contain_file('/etc/init.d/vault') } end context 'install through archive without service management' do let(:params) do { install_method: 'archive', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through archive with service management' do let(:params) do { install_method: 'archive', manage_service_file: true } end it { is_expected.to contain_file('/etc/init.d/vault') } end end when 7 context 'RedHat >=7 specific' do let :facts do facts.merge(service_provider: 'systemd', processorcount: 3) end context 'includes systemd init script' do it { is_expected.to contain_file('/etc/systemd/system/vault.service'). with_mode('0444'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^# vault systemd unit file}). with_content(%r{^User=vault$}). with_content(%r{^Group=vault$}). with_content(%r{Environment=GOMAXPROCS=3}). with_content(%r{^ExecStart=/usr/local/bin/vault server -config=/etc/vault/config.json $}). with_content(%r{SecureBits=keep-caps}). with_content(%r{Capabilities=CAP_IPC_LOCK\+ep}). with_content(%r{CapabilityBoundingSet=CAP_SYSLOG CAP_IPC_LOCK}). with_content(%r{NoNewPrivileges=yes}) } end context 'service with non-default options' do let(:params) do { bin_dir: '/opt/bin', config_dir: '/opt/etc/vault', service_options: '-log-level=info', user: 'root', group: 'admin', num_procs: 8 } end it { is_expected.to contain_file('/etc/systemd/system/vault.service'). with_mode('0444'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^# vault systemd unit file}). with_content(%r{^User=root$}). with_content(%r{^Group=admin$}). with_content(%r{Environment=GOMAXPROCS=8}). with_content(%r{^ExecStart=/opt/bin/vault server -config=/opt/etc/vault/config.json -log-level=info$}) } end context 'with mlock disabled' do let(:params) do { disable_mlock: true } end it { is_expected.to contain_file('/etc/systemd/system/vault.service'). with_mode('0444'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^# vault systemd unit file}). with_content(%r{^User=vault$}). with_content(%r{^Group=vault$}). with_content(%r{^ExecStart=/usr/local/bin/vault server -config=/etc/vault/config.json $}). without_content(%r{SecureBits=keep-caps}). without_content(%r{Capabilities=CAP_IPC_LOCK\+ep}). with_content(%r{CapabilityBoundingSet=CAP_SYSLOG}). with_content(%r{NoNewPrivileges=yes}) } end context 'includes systemd magic' do it { is_expected.to contain_class('systemd') } end context 'install through repo with default service management' do let(:params) do { install_method: 'repo', manage_service_file: :undef } end it { is_expected.not_to contain_file('/etc/systemd/system/vault.service') } end context 'install through repo without service management' do let(:params) do { install_method: 'repo', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/systemd/system/vault.service') } end context 'install through repo with service management' do let(:params) do { install_method: 'repo', manage_service_file: true } end it { is_expected.to contain_file('/etc/systemd/system/vault.service') } end context 'install through archive with default service management' do let(:params) do { install_method: 'archive', manage_service_file: :undef } end it { is_expected.to contain_file('/etc/systemd/system/vault.service') } end context 'install through archive without service management' do let(:params) do { install_method: 'archive', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/systemd/system/vault.service') } end context 'install through archive with service management' do let(:params) do { install_method: 'archive', manage_service_file: true } end it { is_expected.to contain_file('/etc/systemd/system/vault.service') } end end end when 'Debian' context 'on Debian OS family' do context 'with upstart' do let :facts do facts.merge(service_provider: 'upstart', processorcount: 3) end context 'includes init link to upstart-job' do it { is_expected.to contain_file('/etc/init.d/vault'). with_ensure('link'). with_target('/lib/init/upstart-job'). with_mode('0755') } end context 'contains /etc/init/vault.conf' do it { is_expected.to contain_file('/etc/init/vault.conf'). with_mode('0444'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^# vault Agent \(Upstart unit\)}). with_content(%r{env USER=vault}). with_content(%r{env GROUP=vault}). with_content(%r{env CONFIG=\/etc\/vault\/config.json}). with_content(%r{env VAULT=\/usr\/local\/bin\/vault}). with_content(%r{exec start-stop-daemon -u \$USER -g \$GROUP -p \$PID_FILE -x \$VAULT -S -- server -config=\$CONFIG $}). with_content(%r{export GOMAXPROCS=\${GOMAXPROCS:-3}}) } end end context 'service with modified options and sysv init' do let :facts do facts.merge(service_provider: 'init') end let(:params) do { bin_dir: '/opt/bin', config_dir: '/opt/etc/vault', service_options: '-log-level=info', user: 'root', group: 'admin' } end it { is_expected.to contain_exec('setcap cap_ipc_lock=+ep /opt/bin/vault'). with_unless('getcap /opt/bin/vault | grep cap_ipc_lock+ep'). that_subscribes_to('File[/opt/bin/vault]') } it { is_expected.to contain_file('/opt/etc/vault/config.json') } it { is_expected.to contain_file('/opt/bin/vault').with_mode('0755') } it { is_expected.to contain_file('/opt/etc/vault'). with_ensure('directory'). with_purge('true'). \ with_recurse('true') } it { is_expected.to contain_user('root') } it { is_expected.to contain_group('admin') } end context 'install through repo with default service management' do let(:params) do { install_method: 'repo', manage_service_file: :undef } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through repo without service management' do let(:params) do { install_method: 'repo', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through repo with service management' do let(:params) do { install_method: 'repo', manage_service_file: true } end it { is_expected.to contain_file('/etc/init.d/vault') } end context 'install through archive with default service management' do let(:params) do { install_method: 'archive', manage_service_file: :undef } end it { is_expected.to contain_file('/etc/init.d/vault') } end context 'install through archive without service management' do let(:params) do { install_method: 'archive', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/init.d/vault') } end context 'install through archive with service management' do let(:params) do { install_method: 'archive', manage_service_file: true } end it { is_expected.to contain_file('/etc/init.d/vault') } end context 'on Debian based with systemd' do let :facts do facts.merge(service_provider: 'systemd', processorcount: 3) end context 'includes systemd init script' do it { is_expected.to contain_file('/etc/systemd/system/vault.service'). with_mode('0444'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^# vault systemd unit file}). with_content(%r{^User=vault$}). with_content(%r{^Group=vault$}). with_content(%r{Environment=GOMAXPROCS=3}). with_content(%r{^ExecStart=/usr/local/bin/vault server -config=/etc/vault/config.json $}). with_content(%r{SecureBits=keep-caps}). with_content(%r{Capabilities=CAP_IPC_LOCK\+ep}). with_content(%r{CapabilityBoundingSet=CAP_SYSLOG CAP_IPC_LOCK}). with_content(%r{NoNewPrivileges=yes}) } end context 'service with non-default options' do let(:params) do { bin_dir: '/opt/bin', config_dir: '/opt/etc/vault', service_options: '-log-level=info', user: 'root', group: 'admin', num_procs: 8 } end it { is_expected.to contain_file('/etc/systemd/system/vault.service'). with_mode('0444'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^# vault systemd unit file}). with_content(%r{^User=root$}). with_content(%r{^Group=admin$}). with_content(%r{Environment=GOMAXPROCS=8}). with_content(%r{^ExecStart=/opt/bin/vault server -config=/opt/etc/vault/config.json -log-level=info$}) } end context 'with mlock disabled' do let(:params) do { disable_mlock: true } end it { is_expected.to contain_file('/etc/systemd/system/vault.service'). with_mode('0444'). with_ensure('file'). with_owner('root'). with_group('root'). with_content(%r{^# vault systemd unit file}). with_content(%r{^User=vault$}). with_content(%r{^Group=vault$}). with_content(%r{^ExecStart=/usr/local/bin/vault server -config=/etc/vault/config.json $}). without_content(%r{SecureBits=keep-caps}). without_content(%r{Capabilities=CAP_IPC_LOCK\+ep}). with_content(%r{CapabilityBoundingSet=CAP_SYSLOG}). with_content(%r{NoNewPrivileges=yes}) } end it { is_expected.to contain_systemd__unit_file('vault.service') } context 'install through repo with default service management' do let(:params) do { install_method: 'repo', manage_service_file: :undef } end it { is_expected.not_to contain_file('/etc/systemd/system/vault.service') } end context 'install through repo without service management' do let(:params) do { install_method: 'repo', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/systemd/system/vault.service') } end context 'install through repo with service management' do let(:params) do { install_method: 'repo', manage_service_file: true } end it { is_expected.to contain_file('/etc/systemd/system/vault.service') } end context 'install through archive with default service management' do let(:params) do { install_method: 'archive', manage_service_file: :undef } end it { is_expected.to contain_file('/etc/systemd/system/vault.service') } end context 'install through archive without service management' do let(:params) do { install_method: 'archive', manage_service_file: false } end it { is_expected.not_to contain_file('/etc/systemd/system/vault.service') } end context 'install through archive with service management' do let(:params) do { install_method: 'archive', manage_service_file: true } end it { is_expected.to contain_file('/etc/systemd/system/vault.service') } end end end end end end end
class ZillowSearch include Capybara::DSL def listings css_selector = '.zsg-photo-card-overlay-link' find_all(css_selector) end def next_page within find('.zsg-pagination') do begin find('.zsg-pagination_active+li').click rescue Capybara::ElementNotFound return "end" end end end def max_page attempt = 1 begin within find('.zsg-pagination') do all('.zsg-pagination-ellipsis+li').last.text end rescue puts "can't find it, retrying #{attempt}" if attempt < 3 attempt = attempt + 1 retry end end end def current_page within find('.zsg-pagination') do find('.zsg-pagination_active').text end end end
module Ricer::Plug::Extender::ForcesAuthentication OPTIONS ||= { always: true } def forces_authentication(options={always:true}) class_eval do |klass| merge_options(options, OPTIONS) klass.register_exec_function(:exec_auth_check!) if options[:always] def passes_auth_check? !failed_auth_check? end def failed_auth_check? (user.registered?) && (!user.authenticated?) end def auth_check_text I18n.t('ricer.plug.extender.forces_authentication.err_authenticate') end def exec_auth_check! if failed_auth_check? raise Ricer::ExecutionException.new(auth_check_text) end end end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) require 'open-uri' url = 'http://www.languagedaily.com/learn-german/vocabulary/common-german-words' doc = Nokogiri::HTML(open(url)) rows = doc.search(".rowA, .rowB") cards = rows.map do |row| columns = row.css("td") { original_text: columns[1].text, translated_text: columns[2].text, review_date: Date.today.next_day(rand(3)) } end user = User.find_by(email: "erdeuz@gmail.com") user ||= User.new(email: "erdeuz@gmail.com", password: "asd", password_confirmation: "asd") user.save if user.new_record? deck = user.decks.find_by(name: 'german words') || user.decks.new(name: 'german words', description: 'Most Common German Words') deck.save if deck.new_record? deck.cards.destroy_all deck.cards.create(cards)
class ChangeMenusRecipeIdNull < ActiveRecord::Migration[5.2] def change change_column_null :menus, :recipe_id, true end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Adapter::Adapters::Movie do describe '.new' do subject(:subject_class) { described_class.new(value) } context 'when params is valid' do let(:value) { { query: 'query' } } it 'response with valid array keys' do expect(subject_class.query).to eql(value[:query]) end end end describe '.call' do subject(:subject_class) { described_class.new(value).call } let(:response) { JSON(subject_class.body) } let(:data) { JSON(subject_class.body)['data'].first } context 'call describe class with movie type' do let(:value) { { query: 1724 } } let(:title) { 'The Incredible Hulk' } it 'response with valid status' do VCR.use_cassette(title, record: :once) do expect(subject_class.status).to eql(200) end end it 'response with valid movie infos' do VCR.use_cassette(title, record: :once) do expect(response.keys).to match_array(%w[metadata data]) expect(data['id']).to eql(value[:query]) expect(data['title']).to eql(title) expect(data['genres']).to eql([878, 28, 12]) expect(data['cast']).to eql([819, 882, 3129, 227, 1462, 15_232, 68_277]) end end end context 'call describe class with inexisten cast' do let(:value) { { query: -1 } } let(:title) { 'Not existent movie' } it 'response with valid status' do VCR.use_cassette(title, record: :once) do expect(subject_class.status).to eql(200) end end it 'response with valid movie infos' do VCR.use_cassette(title, record: :once) do expect(data).to be_nil end end end context 'call describe class with 500 error' do let(:value) { { query: -1 } } let(:title) { '500_movie' } it 'response with valid status' do VCR.use_cassette(title, record: :once) do expect(subject_class.status).to eql(500) end end end end end
class PostPolicy < ApplicationPolicy attr_reader :user, :post class Scope < Scope def resolve scope.all end end def initialize(user, post) @user = user @post = post end def edit? user.owner_admin?(@post) end def update? user.owner_admin?(@post) end def destroy? user.owner_admin?(@post) end end
require "omniauth" require "omniauth-bookingsync" require "bookingsync-api" module BookingSync class Engine < ::Rails::Engine initializer "bookingsync.add_omniauth" do |app| app.middleware.use OmniAuth::Builder do provider :bookingsync, ::BookingSyncEngine.support_multi_applications? ? nil : ENV["BOOKINGSYNC_APP_ID"], ::BookingSyncEngine.support_multi_applications? ? nil : ENV["BOOKINGSYNC_APP_SECRET"], scope: ENV["BOOKINGSYNC_SCOPE"], iframe: ENV.fetch("BOOKINGSYNC_IFRAME", false), setup: -> (env) { if url = ENV["BOOKINGSYNC_URL"] env["omniauth.strategy"].options[:client_options].site = url end env["omniauth.strategy"].options[:client_options].ssl = { verify: ENV["BOOKINGSYNC_VERIFY_SSL"] != "false" } if ::BookingSyncEngine.support_multi_applications? credentials = BookingSync::Engine::CredentialsResolver.new(env["HTTP_HOST"]).call if credentials.valid? env["omniauth.strategy"].options[:client_id] = credentials.client_id env["omniauth.strategy"].options[:client_secret] = credentials.client_secret end end } end end initializer "bookingsync.controller_helper" do |app| require "bookingsync/engine/helpers" require "bookingsync/engine/session_helpers" require "bookingsync/engine/auth_helpers" ActiveSupport.on_load :action_controller do include BookingSync::Engine::Helpers include BookingSync::Engine::SessionHelpers include BookingSync::Engine::AuthHelpers end end # @return [Boolean] cattr_accessor :embedded self.embedded = true # Duration of inactivity after which the authorization will be reset. # See {BookingSync::Engine::SessionHelpers#sign_out_if_inactive}. # @return [Fixnum] cattr_accessor :sign_out_after self.sign_out_after = 10.minutes # Set the engine into embedded mode. # # Embedded apps are loaded from within the BookingSync app store, and # have a different method to redirect during the OAuth authorization # process. <b>This method will not work when the app is not embedded</b>. def self.embedded! self.embedded = true end # Set the engine into standalone mode. # # This setting is requried for the applications using this Engine # to work outside of the BookingSync app store. # # Restores the normal mode of redirecting during OAuth authorization. def self.standalone! self.embedded = false end # OAuth client configured for the application. # # The ENV variables used for configuration are described in {file:README.md}. # # @return [OAuth2::Client] configured OAuth client def self.oauth_client(client_id: ENV["BOOKINGSYNC_APP_ID"], client_secret: ENV["BOOKINGSYNC_APP_SECRET"]) connection_options = { headers: { accept: "application/vnd.api+json" } }.merge(::BookingSyncEngine.oauth_client_connection_options) client_options = { site: ENV["BOOKINGSYNC_URL"] || 'https://www.bookingsync.com', connection_opts: connection_options } client_options[:ssl] = { verify: ENV['BOOKINGSYNC_VERIFY_SSL'] != 'false' } OAuth2::Client.new(client_id, client_secret, client_options) end def self.application_token(client_id: ENV["BOOKINGSYNC_APP_ID"], client_secret: ENV["BOOKINGSYNC_APP_SECRET"]) token_refresh_timeout_attempts_allowed = ::BookingSyncEngine.token_refresh_timeout_retry_count + 1 BookingSync::Engine::Retryable.perform(times: token_refresh_timeout_attempts_allowed, errors: [Faraday::TimeoutError]) do oauth_client(client_id: client_id, client_secret: client_secret).client_credentials.get_token end end end end require "bookingsync/engine/application_credentials" require "bookingsync/engine/credentials_resolver" require "bookingsync/engine/api_client" require "bookingsync/engine/models" require "bookingsync/engine/retryable"
# frozen_string_literal: true module Kenui VERSION = '2.0.1' end
# # spec'ing rufus-verbs # # Sat Jul 20 22:32:42 JST 2013 # require 'spec_helper' describe Rufus::Verbs do before(:each) do start_test_server end after(:each) do stop_test_server end describe '.get' do it 'accepts the URI directly' do r = Rufus::Verbs.get('http://localhost:7777/items') r.code.should == '200' r.body.should == "{}\n" r['Content-Length'].should == '3' end it 'accepts the URI via the :uri option' do r = Rufus::Verbs.get(:uri => 'http://localhost:7777/items') r.code.should == '200' r.body.should == "{}\n" r['Content-Length'].should == '3' end it 'accepts the URI via the :u option' do r = Rufus::Verbs.get(:u => 'http://localhost:7777/items') r.code.should == '200' r.body.should == "{}\n" r['Content-Length'].should == '3' end it 'accepts a URI::HTTP instance' do r = Rufus::Verbs.get(URI.parse('http://localhost:7777/items')) r.code.should == '200' r.body.should == "{}\n" r['Content-Length'].should == '3' end it 'accepts a :host/:port/:path combination' do r = Rufus::Verbs.get( :host => 'localhost', :port => 7777, :path => '/items') r.code.should == '200' r.body.should == "{}\n" r['Content-Length'].should == '3' end it 'is ok with a URI without a path' do r = Rufus::Verbs.get('http://rufus.rubyforge.org') r.class.should == Net::HTTPOK end context ':body => true' do it 'returns the body directly (not the HTTPResponse)' do r = Rufus::Verbs.get('http://localhost:7777/items', :body => true) r.should == "{}\n" end end context ':timeout => seconds' do it 'times out after the given time' do t = Time.now lambda { Rufus::Verbs.get 'http://localhost:7777/lost', :to => 1 }.should raise_error(Timeout::Error) (Time.now - t).should < 2 end end context 'redirections' do it 'follows redirections by default' do r = Rufus::Verbs.get('http://localhost:7777/things') r.code.should == '200' r.body.should == "{}\n" end it 'accepts a :no_redirections => true option' do r = Rufus::Verbs.get( 'http://localhost:7777/things', :no_redirections => true) r.code.should == '303' end it 'accepts a :noredir => true option' do r = Rufus::Verbs.get( 'http://localhost:7777/things', :noredir => true) r.code.should == '303' end end end describe '.post' do it 'posts data to a URI' do r = Rufus::Verbs.post('http://localhost:7777/items', :d => 'Toto') r.code.should == '201' r['Location'].should == 'http://localhost:7777/items/0' r = Rufus::Verbs.get('http://localhost:7777/items/0') r.body.should == "\"Toto\"\n" end it 'accepts a block returning the data to post' do r = Rufus::Verbs.post('http://localhost:7777/items') do "nada" * 3 end r.code.should == '201' r['Location'].should == 'http://localhost:7777/items/0' r = Rufus::Verbs.get('http://localhost:7777/items/0') r.body.should == "\"nadanadanada\"\n" end end describe '.put' do before(:each) do Rufus::Verbs.post('http://localhost:7777/items', :d => 'Toto') end it 'puts data to a URI' do r = Rufus::Verbs.put('http://localhost:7777/items/0', :d => 'Toto2') r.code.should == '200' r = Rufus::Verbs.get('http://localhost:7777/items/0') r.body.should == "\"Toto2\"\n" end it 'accepts a block returning the data to put' do r = Rufus::Verbs.put('http://localhost:7777/items/0') do 'xxx' end r.code.should == '200' r = Rufus::Verbs.get('http://localhost:7777/items/0') r.body.should == "\"xxx\"\n" end context ':fake_put => true' do it 'uses POST behind the scenes' do r = Rufus::Verbs.put( 'http://localhost:7777/items/0', :fake_put => true, :d => 'Maurice') r.code.should == '200' r = Rufus::Verbs.get('http://localhost:7777/items') r.body.should == "{0=>\"Maurice\"}\n" end end end describe '.head' do it 'behaves like .get but does not fetch the body' do r = Rufus::Verbs.head('http://localhost:7777/items') r.code.should == '200' r.body.should == nil end end describe '.options' do it 'lists the HTTP methods the endpoint responds to' do r = Rufus::Verbs.options('http://localhost:7777/items') r.should == [ :delete, :get, :head, :options, :post, :put ] end end end
class Admin::AudioContentsController < ApplicationController before_filter :require_admin! # GET /audio_contents # GET /audio_contents.json def index @audio_contents = AudioContent.all @audio_mp3s = AudioMp3.all respond_to do |format| format.html # index.html.erb format.json { render json: @audio_contents } end end # GET /audio_contents/1 # GET /audio_contents/1.json def show @audio_content = AudioContent.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @audio_content } end end # GET /audio_contents/new # GET /audio_contents/new.json def new @audio_content = AudioContent.new 3.times {@audio_content.audio_mp3s.build} respond_to do |format| format.html # new.html.erb format.json { render json: @audio_content } end end # GET /audio_contents/1/edit def edit @audio_content = AudioContent.find(params[:id]) 3.times {@audio_content.audio_mp3s.build} end # POST /audio_contents # POST /audio_contents.json def create @audio_content = AudioContent.new(params[:audio_content]) respond_to do |format| if @audio_content.save format.html { redirect_to admin_audio_contents_url, notice: 'Audio content was successfully created.' } format.json { render json: @audio_content, status: :created, location: @audio_content } else format.html { render action: "new" } format.json { render json: @audio_content.errors, status: :unprocessable_entity } end end end # PUT /audio_contents/1 # PUT /audio_contents/1.json def update @audio_content = AudioContent.find(params[:id]) respond_to do |format| if @audio_content.update_attributes(params[:audio_content]) format.html { redirect_to audio_content_path(@audio_content), notice: 'Audio content was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @audio_content.errors, status: :unprocessable_entity } end end end # DELETE /audio_contents/1 # DELETE /audio_contents/1.json def destroy @audio_content = AudioContent.find(params[:id]) @audio_mp3s = AudioMp3.find_all_by_audio_content_id([@audio_content.id]) @audio_mp3s.each do |audio_mp3| audio_mp3.destroy end @audio_content.destroy respond_to do |format| format.html { redirect_to admin_audio_contents_url } format.json { head :no_content } end end def display @audio_contents = AudioContent.all @page = Page.where(:url => "/display").first respond_to do |format| format.html # index.html.erb format.json { render json: @audio_contents } end end end
module Apohypaton class ServiceValidationException < StandardError end class ServiceExistsException < StandardError end class ServiceRegistrationException < StandardError end class Service include ActiveModel::Model include ActiveModel::Serialization attr_accessor :name, :checks, :port, :tags validates_presence_of :name validates_format_of :name, with: /\A[a-z][a-z0-9\-_]{2,128}\z/i validates :checks, length: { maximum: 32 }, presence: true validates :tags, length: { maximum: 32 }, presence: true validates_inclusion_of :port, in: 1..65000 validates_numericality_of :port, only_integer: true def self.hosts(service_name, tags) data_centers = Diplomat::Datacenter.get services = data_centers.map { |dc| Diplomat::Service.get(service_name, :all, :dc => dc) }.flatten return services if tags.blank? services.select { |service| Set.new(service.ServiceTags) >= Set.new(tags) } end def initialize(arguments={}) super @config = Apohypaton.configuration end def attributes { 'name' => nil, 'tags' => nil, 'port' => nil } end def save! create_or_update! end def create_or_update! unless persisted? create! else update! end end def create! raise Apohypaton::ServiceValidationException.new(self.errors.messages) unless self.valid? raise Apohypaton::ServiceExistsException.new("Service #{@name} already exists") if self.persisted? begin Diplomat::Service.register self.serializable_hash @checks.each do |check| check.serviceid = @name check.save! end rescue Faraday::ClientError => e raise Apohypaton::ServiceRegistrationException.new(e.message) end end def update! raise Apohypaton::ServiceValidationException.new(self.errors) unless self.valid? raise Apohypaton::ImmutableServiceProperty.new("Service tags and port are immutable") if changed['Tags'] || changed['Port'] @checks.each do |check| check.serviceid = @name check.save! end end def destroy! Diplomat::Service.deregister @name end def persisted resp = Diplomat::Node.get(`hostname`.strip) node_services = resp['Services'] || {} node_services.select { |s, _| s == @name }.first end def persisted? persisted ? true : false end def changed begin { port: persisted[1]['Tags'] == @tags, tags: persisted[1]['Port'] == @port, } rescue NoMethodError { port: true, tags: true } end end def changed? unless persisted? true else unless changed.select { |_, v| v == true }.empty? true else false end end end def self.create_from_yaml_file(fname) env_services = self.load_from_yaml_file(fname) env_services.each do |s| s.save! end env_services end def self.load_from_yaml_file(fname) all_services = YAML.load(ERB.new(File.read(fname)).result) env_services = all_services[Apohypaton.configuration.deploy_env] env_services.map do |s_name, s_attributes| s_attributes["name"] = s_name s = Apohypaton::Service.new(s_attributes) s.checks = s.checks.map { |c| Apohypaton::Check.new(c) } s end end alias_method :register!, :save! end end
class AlterFamiliesAddSaldoPrecision < ActiveRecord::Migration def change change_column :families, :saldo, :decimal, default: 0.00, precision: 2 end end
class GroupMembersController < ApplicationController before_action :authenticate_user! def index group = Group.find(params[:group_id]) members = if params[:recent].present? group.members.accepted.order('created_at DESC').limit(14) else is_staff = current_user && group.is_staff?(current_user) members = is_staff ? group.members : group.members.accepted members.order(pending: :desc, rank: :desc).page(params[:page]).per(20) end render json: members, meta: {cursor: 1 + (params[:page] || 1).to_i} end def create membership_hash = params.require(:group_member).permit(:group_id, :user_id).to_h user = User.find(membership_hash['user_id']) return error! "Wrong user", 403 if user.nil? || current_user != user return error! "Already in group", :conflict if GroupMember.exists?(membership_hash.slice('user_id', 'group_id')) group = Group.find(membership_hash['group_id']) membership = GroupMember.create!( group: group, pending: !group.public?, user: user ) render json: membership, status: :created end def update if current_user.admin? || current_member.admin? membership_hash = params.require(:group_member).permit(:pending, :rank).to_h elsif current_member.mod? membership_hash = params.require(:group_member).permit(:pending).to_h else return error! "Only admins and mods can do that", 403 end # won't apply attributes if we just refer to `membership` private method membership = GroupMember.find(params[:id]) membership.attributes = membership_hash # If they were an admin and their rank is being changed, check that they're not the last admin if membership.rank_changed? && membership.rank_was == 'admin' && !group.can_admin_resign? return error! "Last admin of the group cannot resign", 400 else membership.save! render json: membership end end def destroy return error! "Mods can only remove regular users from the group", 403 unless current_user.admin? || current_member.admin? || (current_member.mod? && membership.pleb?) || current_user.id == membership.user_id return error! "You must promote another admin", 400 if membership.admin? && !group.can_admin_resign? return error! "Wrong user", 403 if current_member.pleb? && current_user.id != membership.user_id membership.destroy render json: {} end private def current_member group.member(current_user) end def group membership.group end def membership GroupMember.find(params[:id]) end end
#!/usr/bin/env ruby # EDOS data building $: << File.expand_path('../', File.dirname(__FILE__)) $: << File.expand_path('../packages', File.dirname(__FILE__)) require 'yaml' require 'std/core_ext' require 'std/mixins' require 'data_model/load' require 'moon-mock/load' require 'std/vector2' require 'std/vector3' require 'std/vector4' require 'std/rect' require 'std/event' require 'std/state' require 'data_bags/load' require 'render_primitives/load' require 'state_mvc/load' require 'twod/load' require 'scripts/camera_cursor' require 'scripts/map_cursor' require 'scripts/models' include Moon require 'scripts/database' require 'scripts/models' require 'scripts/helpers' require 'scripts/mixin' require 'scripts/core_ext/array' require 'scripts/core_ext/dir' require 'scripts/core_ext/enumerable' require 'scripts/core_ext/hash' require 'scripts/core_ext/numeric' require 'scripts/core_ext/string' require 'scripts/core_ext/moon-data_matrix' require 'scripts/core_ext/moon-vector2' require 'scripts/core_ext/moon-vector3' require 'scripts/core_ext/moon-vector4' require 'scripts/const' @pool = [] def pool(obj) @pool << obj end require_relative 'data/characters' #require_relative 'data/chunks' #require_relative 'data/entities' #require_relative 'data/maps' #require_relative 'data/popups' #require_relative 'data/tilesets' Dir.chdir('../') do @pool.each do |obj| obj.validate obj.save_file end end
FactoryGirl.define do factory :song do sequence(:name) {|n| "Name#{n}"} description "Details" end end
class PollsController < ApplicationController before_action :authenticate_user, except: [:index] def index @polls = Poll.all @current_user = current_user end def new end def create params[:poll][:user_id] = current_user.id @poll = Poll.new(poll_params) if @poll.save render json: { success: "Poll Successfully created ", poll: @poll }, status: :ok else render json: { errors: @poll.errors.full_messages }, status: :unprocessable_entity end end private def poll_params params.required(:poll).permit(:title, :user_id, options_attributes: [:name]) end end
class ReportChoice < ActiveRecord::Base belongs_to :report_item has_many :answers has_many :services, :through => :answers end
class Plug::Api CSRF_REGEX = /_csrf ?= ?"(.+?)"/i SOCKET_TOKEN_REGEX = /_jm ?= ?"(.+?)"/i API_BASE = "https://plug.dj/_" attr_reader :http def initialize @http = HTTPClient.new end def login(username, password) main_page = @http.get_content("https://plug.dj") match = CSRF_REGEX.match(main_page) unless match raise "Could not get CSRF token" end csrf_token = match[1] auth_body = { :email => username, :password => password, :csrf => csrf_token } login_req = post_json("#{API_BASE}/auth/login", auth_body) response = JSON.parse(login_req.body) if response["status"] != "ok" raise "Login Failed. Status: #{response["status"]}" end response["data"] end def logout @http.delete("#{API_BASE}/auth/session") end def users_me get_json("#{API_BASE}/users/me") end def join_room(room) post_json("#{API_BASE}/rooms/join", { "slug" => room }) end def rooms_state get_json("#{API_BASE}/rooms/state") end def rooms_history get_json("#{API_BASE}/rooms/history") end def update_status(status_code) put_json("#{API_BASE}/users/status", { "status" => status_code }) end def session_cookie @http.cookies.select do |x| x.domain == "plug.dj" && x.name == "session" end.first end def socket_token(room) room = @http.get("https://plug.dj/#{room}/") if room.redirect? raise "Redirected to #{room.headers["Location"]}. Are you logged in?" end match = SOCKET_TOKEN_REGEX.match(room.body) unless match raise "Unable to find socket token" end match[1] end def logged_in? response = @http.get("#{API_BASE}/users/me") return response.ok? end private def post_json(url, json) headers = { "Content-Type" => "application/json" } @http.post(url, :header => headers, :body => json.to_json) end def put_json(url, json) headers = { "Content-Type" => "application/json" } @http.put(url, :header => headers, :body => json.to_json) end def get_json(url) response = @http.get(url) unless response.ok? raise "Failed to GET #{url}. Returned #{response.code}" end JSON.parse(response.body) end end
class MaintenanceRequestForm < ActiveRecord::Base belongs_to :ref_maintenance_type belongs_to :response_user, :class_name => "User", :foreign_key => "response_user_id" belongs_to :request_user, :class_name => "User", :foreign_key => "request_user_id" belongs_to :machine belongs_to :user before_create :init_status def init_status self.status = "Request" # TODO self.request_user_id = 4 # TODO end end
class TeamSerializer < ActiveModel::Serializer attributes :name, :id, :tournament_id, :owner, :is_owner, :logo, :registration_date def is_owner current_user ? current_user.id == object.user_id : false end def logo object.logo_url end def owner object.user.full_name end def registration_date object.created_at.strftime('%d %B %Y, %H:%M') end end
class Remove < ActiveRecord::Migration def change remove_column :tenants, :status, :string end end
class TasksController < ApplicationController before_filter :authenticate_user! attr_accessor :completed respond_to :html, :xml def index @user = current_user @incomplete = current_user.tasks.incomplete @task = current_user.tasks.new respond_with(@incomplete) end def showall @tasks = Task.all end def show @task = Task.find(params[:id]) end def new @task = Task.new end def create if params[:task][:parent_id]==nil @task = current_user.tasks.new(params[:task]) if @task.save flash[:notice] = "Task Created. Time to get to work..." redirect_to tasks_url else render :action => 'new' end else @task = Task.find(params[:task][:parent_id]) @subtask = @task.children.create(params[:task]) if @subtask.save flash[:notice] = "Task Created. Time to get to work..." redirect_to tasks_url else render :action => 'new' end end end def subtask @task = Task.find(params[:id]) @subtask = @task.children.new end def complete @task = Task.find(params[:id]) @task.completed = true @task.save flash[:notice] = "Hoorray! Task Completed!" redirect_to tasks_url end def edit @task = Task.find(params[:id]) end def update @task = Task.find(params[:id]) if @task.update_attributes(params[:task]) flash[:notice] = "Successfully updated task." redirect_to @task else render :action => 'edit' end end def destroy @task = Task.find(params[:id]) @task.destroy flash[:notice] = "Task terminated." redirect_to '/showall' end end
module Validator # = Validator::Site # Validates the site id class Site < ActiveModel::Validator TRANSLATION_SCOPE = [:errors, :messages] def validate(record) return false if record.site_id.nil? if ::Site.find_by_id(record.site_id).nil? record.errors[:base] << I18n.t(:site, :scope => TRANSLATION_SCOPE) end end end end
license_key = ask("Please enter your NewRelic RPM license key:") template = %Q{ # # This file configures the NewRelic RPM Agent, NewRelic RPM monitors # Rails applications with deep visibility and low overhead. For more # information, visit www.newrelic.com. # # This configuration file is custom generated for aziz # # here are the settings that are common to all environments common: &default_settings # ============================== LICENSE KEY =============================== # You must specify the licence key associated with your New Relic # account. This key binds your Agent's data to your account in the # New Relic RPM service. license_key: "#{license_key}" # Agent Enabled (Rails Only) # Use this setting to force the agent to run or not run. # Default is 'auto' which means the agent will install and run only # if a valid dispatcher such as Mongrel is running. This prevents # it from running with Rake or the console. Set to false to # completely turn the agent off regardless of the other settings. # Valid values are true, false and auto. # agent_enabled: auto # Application Name # Set this to be the name of your application as you'd like it show # up in RPM. RPM will then auto-map instances of your application # into a RPM "application" on your home dashboard page. If you want # to map this instance into multiple apps, like "AJAX Requests" and # "All UI" then specify a semicolon separated list of up to three # distinct names. If you comment this out, it defaults to the # capitalized RAILS_ENV (i.e., Production, Staging, etc) app_name: My Application # When "true", the agent collects performance data about your # application and reports this data to the NewRelic RPM service at # newrelic.com. This global switch is normally overridden for each # environment below. enabled: true # Developer mode should be off in every enviornment but # development as it has very high overhead in memory developer: false # The newrelic agent generates its own log file to keep its logging # information separate from that of your application. Specify its # log level here. log_level: info # The newrelic agent communicates with the RPM service via http by # default. If you want to communicate via https to increase # security, then turn on SSL by setting this value to true. Note, # this will result in increased CPU overhead to perform the # encryption involved in SSL communication, but this work is done # asynchronously to the threads that process your application code, # so it should not impact response times. ssl: false # EXPERIMENTAL: enable verification of the SSL certificate sent by # the server. This setting has no effect unless SSL is enabled # above. This may block your application. Only enable it if the data # you send us needs end-to-end verified certificates. # # This means we cannot cache the DNS lookup, so each request to the # RPM service will perform a lookup. It also means that we cannot # use a non-blocking lookup, so in a worst case, if you have DNS # problems, your app may block indefinitely. # verify_certificate: true # Set your application's Apdex threshold value with the 'apdex_t' # setting, in seconds. The apdex_t value determines the buckets used # to compute your overall Apdex score. # Requests that take less than apdex_t seconds to process will be # classified as Satisfying transactions; more than apdex_t seconds # as Tolerating transactions; and more than four times the apdex_t # value as Frustrating transactions. # For more about the Apdex standard, see # http://support.newrelic.com/faqs/general/apdex apdex_t: 0.5 # Proxy settings for connecting to the RPM server. # # If a proxy is used, the host setting is required. Other settings # are optional. Default port is 8080. # # proxy_host: hostname # proxy_port: 8080 # proxy_user: # proxy_pass: # Tells transaction tracer and error collector (when enabled) # whether or not to capture HTTP params. When true, frameworks can # exclude HTTP parameters from being captured. # Rails: the RoR filter_parameter_logging excludes parameters # Java: create a config setting called "ignored_params" and set it to # a comma separated list of HTTP parameter names. # ex: ignored_params: credit_card, ssn, password capture_params: false # Transaction tracer captures deep information about slow # transactions and sends this to the RPM service once a # minute. Included in the transaction is the exact call sequence of # the transactions including any SQL statements issued. transaction_tracer: # Transaction tracer is enabled by default. Set this to false to # turn it off. This feature is only available at the Silver and # above product levels. enabled: true # Threshold in seconds for when to collect a transaction # trace. When the response time of a controller action exceeds # this threshold, a transaction trace will be recorded and sent to # RPM. Valid values are any float value, or (default) "apdex_f", # which will use the threshold for an dissatisfying Apdex # controller action - four times the Apdex T value. transaction_threshold: apdex_f # When transaction tracer is on, SQL statements can optionally be # recorded. The recorder has three modes, "off" which sends no # SQL, "raw" which sends the SQL statement in its original form, # and "obfuscated", which strips out numeric and string literals record_sql: obfuscated # Threshold in seconds for when to collect stack trace for a SQL # call. In other words, when SQL statements exceed this threshold, # then capture and send to RPM the current stack trace. This is # helpful for pinpointing where long SQL calls originate from stack_trace_threshold: 0.500 # Determines whether the agent will capture query plans for slow # SQL queries. Only supported in mysql and postgres. Should be # set to false when using other adapters. # explain_enabled: true # Threshold for query execution time below which query plans will not # not be captured. Relevant only when `explain_enabled` is true. # explain_threshold: 0.5 # Error collector captures information about uncaught exceptions and # sends them to RPM for viewing error_collector: # Error collector is enabled by default. Set this to false to turn # it off. This feature is only available at the Silver and above # product levels enabled: true # Rails Only - tells error collector whether or not to capture a # source snippet around the place of the error when errors are View # related. capture_source: true # To stop specific errors from reporting to RPM, set this property # to comma separated values # #ignore_errors: ActionController::RoutingError, ... # (Advanced) Uncomment this to ensure the cpu and memory samplers # won't run. Useful when you are using the agent to monitor an # external resource # disable_samplers: true # Application Environments # ------------------------------------------ # Environment specific settings are in this section. # For Rails applications, RAILS_ENV is used to determine the environment # For Java applications, pass -Dnewrelic.environment <environment> to set # the environment # NOTE if your application has other named environments, you should # provide newrelic conifguration settings for these enviromnents here. development: <<: *default_settings # Turn off communication to RPM service in development mode. # NOTE: for initial evaluation purposes, you may want to temporarily # turn the agent on in development mode. enabled: false # Rails Only - when running in Developer Mode, the New Relic Agent will # present performance information on the last 100 transactions you have # executed since starting the mongrel. to view this data, go to # http://localhost:3000/newrelic developer: true test: <<: *default_settings # It almost never makes sense to turn on the agent when running # unit, functional or integration tests or the like. enabled: false # Turn on the agent in production for 24x7 monitoring. NewRelic # testing shows an average performance impact of < 5 ms per # transaction, you you can leave this on all the time without # incurring any user-visible performance degredation. production: <<: *default_settings enabled: true # Many applications have a staging environment which behaves # identically to production. Support for that environment is provided # here. By default, the staging environment has the agent turned on. staging: <<: *default_settings enabled: true app_name: My Application (Staging) } plugin 'rpm', :git => 'git://github.com/newrelic/rpm.git' file "config/newrelic.yml", template git :add => "." git :commit => "-a -m 'Added NewRelic RPM plugin and relic.yml file'"
class Api::V1::HackathonsController < ApplicationController before_action :find_hackathon, only: [:update] def index @hackathons = Hackathon.all render json: @hackathons end def update @hackathon.update(hackathon_params) if @hackathon.save render json: @hackathon, status: :accepted else render json: { errors: @hackathon.errors.full_messages }, status: :unprocessible_entity end end private def hackathon_params params.permit(:title, :date) end def find_hackathon @hackathon = Hackathon.find(params[:id]) end end
# frozen_string_literal: true require 'faker' class User < ApplicationRecord VALID_EMAIL_REGEX = /\A([^@\s]{1,64})@((?:[-\p{L}\d]+\.)+\p{L}{2,})\z/i before_create :set_default_role devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable has_many :messages, dependent: :destroy has_many :rooms, through: :messages has_and_belongs_to_many :roles has_many :room_user_nicknames, dependent: :destroy has_many :moderatorships, dependent: :destroy has_many :muted_room_users, dependent: :destroy validates :username, presence: true, uniqueness: true, length: { minimum: 3, maximum: 64 } validates :email, presence: true, uniqueness: true, format: { with: VALID_EMAIL_REGEX } scope :not_anonymous, -> { includes(:roles).where.not(roles_users: { role_id: Role.anonymous.id.to_s })} def role?(role) roles.include?(role) end def nickname_in_room(room) return 'OP' if room.owner_id == id return ENV['VICTORIOUSBORN_NICKNAME'] if ENV['VICTORIOUSBORN_NICKNAME'].present? && username == 'victoriousBorn' in_room_user_nicknames = RoomUserNickname.includes(:user).where(room: room) nickname_in_room = in_room_user_nicknames.find { |room_user_nickname| room_user_nickname.user == self } return nickname_in_room.nickname unless nickname_in_room.nil? nickname_in_room = loop do nickname = [ Faker::Space.planet, Faker::Space.moon, Faker::Space.galaxy, Faker::Space.star, Faker::TvShows::Stargate.planet, Faker::Movies::StarWars.planet, Faker::Games::Witcher.location ].sample break RoomUserNickname.create!( user: self, nickname: nickname, room: room ) unless RoomUserNickname.exists?( room: room, nickname: nickname ) end nickname_in_room.nickname end def muted_in_room?(room) @muted_in_room_all ||= MutedRoomUser.includes(:user).where(room: room) @muted_in_room_all.find { |muted_in_room| muted_in_room.user == self } .present? end private def set_default_role unless roles.include?(Role.anonymous) roles << Role.registered end end end
require_relative '../../spec_helper' feature "Invitations flow" do let (:gm) {FactoryGirl.create(:dungeonmaster, username: "gamemaester")} let (:user1) {FactoryGirl.create(:user, username: "filthyanimal")} let (:user2) {FactoryGirl.create(:user, username: "partyanimal")} scenario "gamemaster of campaign invites other users to a campaign" do login_as(gm) visit("/") page.has_content?("DASHBOARD") click_link "fartbags" find(".test-invite-users").click fill_in "Usernames", with: "#{user1.username}, #{user2.username}" fill_in "Invitation message body", with: "Hey broham, let's play pathfinder" find(".test-send-invites").click logout login_as(user1) visit "/" assert page.has_content?("1 Invitations") logout login_as(user2) visit "/" assert page.has_content?("1 Invitations") end end
class AddAfternoonToMeetingRooms < ActiveRecord::Migration[5.0] def change add_column :meeting_rooms, :afternoon, :boolean end end
require 'rails_helper' RSpec.describe 'Cities API' do let!(:country) { create(:country) } let!(:state) { create(:state, country_id:country.id) } let!(:cities) { create_list(:city, 10, state_id:state_id)} let(:country_id) { country.id } let(:state_id) { state.id } let(:id) { cities.first.id } describe 'GET /countries/:country_id/states/:state_id/cities' do before { get "/countries/#{country_id}/states/#{state_id}/cities"} context 'when state exists' do it 'returns status code 200' do expect(response).to have_http_status(200) end it 'returns all cities' do expect(json.size).to eq(10) end end end end
require "formula" require "language/go" class Mongodb < Formula homepage "https://www.mongodb.org/" stable do url "https://fastdl.mongodb.org/src/mongodb-src-r3.2.0.tar.gz" sha256 "c6dd1d1670b86cbf02a531ddf7a7cda8f138d8733acce33766f174bd1e5ab2ee" go_resource "github.com/mongodb/mongo-tools" do url "https://github.com/mongodb/mongo-tools.git", :tag => "r3.2.0", :revision => "6186100ad0500c122a56f0a0e28ce1227ca4fc88" end end version '3.2.0-boxen1' bottle do revision 2 sha256 "0dde2411b7dc3ca802449ef276e3d5729aa617b4b7c1fe5712052c1d8f03f28e" => :el_capitan sha256 "a7b91ff62121d66ca77053c9d63234b35993761e620399bd245c8109b9c8f96d" => :yosemite sha256 "65d09370cff5f3c120ec91c8aef44f7bd42bd3184ca187e814c59a2750823558" => :mavericks end devel do url "http://downloads.mongodb.org/osx/mongodb-osx-x86_64-3.0.8-rc0.tgz" sha256 "7a54d48d07fed6216aba10b55c42c804c742790b59057a3d14455e9e99007516" end head "https://github.com/mongodb/mongo.git" option "with-boost", "Compile using installed boost, not the version shipped with mongodb" depends_on "go" => :build depends_on "scons" => :build depends_on "boost" => :optional depends_on "openssl" => :optional depends_on :macos => :mavericks def install # Updates from https://github.com/Homebrew/homebrew/blob/master/Library/Formula/mongodb.rb # New Go tools have their own build script but the server scons "install" target is still # responsible for installing them. Language::Go.stage_deps resources, buildpath/"src" cd "src/github.com/mongodb/mongo-tools" do # https://github.com/Homebrew/homebrew/issues/40136 inreplace "build.sh", '-ldflags "-X github.com/mongodb/mongo-tools/common/options.Gitspec `git rev-parse HEAD`"', "" args = %W[] if build.with? "openssl" args << "ssl" ENV["LIBRARY_PATH"] = "#{Formula["openssl"].opt_prefix}/lib" ENV["CPATH"] = "#{Formula["openssl"].opt_prefix}/include" end system "./build.sh", *args end mkdir "src/mongo-tools" cp Dir["src/github.com/mongodb/mongo-tools/bin/*"], "src/mongo-tools/" args = %W[ --prefix=#{prefix} -j#{ENV.make_jobs} --osx-version-min=#{MacOS.version} ] args << "CC=#{ENV.cc}" args << "CXX=#{ENV.cxx}" args << "--use-sasl-client" if build.with? "sasl" args << "--use-system-boost" if build.with? "boost" args << "--use-new-tools" args << "--disable-warnings-as-errors" if MacOS.version >= :yosemite if build.with? "openssl" args << "--ssl" << "--extrapath=#{Formula["openssl"].opt_prefix}" end scons "install", *args (buildpath+"mongod.conf").write mongodb_conf etc.install "mongod.conf" (var+"mongodb").mkpath (var+"log/mongodb").mkpath end def mongodb_conf; <<-EOS.undent systemLog: destination: file path: #{var}/log/mongodb/mongo.log logAppend: true storage: dbPath: #{var}/mongodb net: bindIp: 127.0.0.1 EOS end test do system "#{bin}/mongod", "--sysinfo" end end
class DropHairCoefficientsTable < ActiveRecord::Migration def change drop_table :haircoefficients end end
module UI module Widgets class RadioEvent < Moon::Event include Moon::UiEvent def initialize(parent) @parent = parent @target = parent super :radio end end end end
shared_examples "require_sign_in" do it "redirects user to the front page if they are not signed in" do clear_current_user action response.should redirect_to front_page_path end end
class CreateTickets < ActiveRecord::Migration[5.0] def change create_table :tickets do |t| t.string :address t.string :name t.integer :phone t.string :email t.string :selection t.integer :flat_nr t.integer :user_id t.string :content t.string :subject t.timestamps end end end
class C0200 attr_reader :options, :name, :field_type, :node def initialize @name = "Repetition of Three Words: List three words ('sock', 'blue', 'bed') for resident; number of words repeated after first attempt (C0200)" @field_type = DROPDOWN @node = "C0200" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("0", "None") @options << FieldOption.new("1", "One") @options << FieldOption.new("2", "Two") @options << FieldOption.new("3", "Three") end def set_values_for_type(klass) return "^" end end
module Fog module Compute class Google class InstanceTemplate < Fog::Model identity :name attribute :kind attribute :self_link, :aliases => "selfLink" attribute :description # Properties is a hash describing the templates # A minimal example is # :properties => { # :machine_type => TEST_MACHINE_TYPE, # :disks => [{ # :boot => true, # :initialize_params => { # :source_image => "projects/ubuntu-os-cloud/global/images/ubuntu-1804-bionic-v20180522"} # }], # :network_interfaces => [{ # :network => "global/networks/default" # }] # } # } # @see https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert attribute :properties def save requires :name requires :properties data = service.insert_instance_template(name, properties, description) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :name data = service.delete_instance_template(name) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } unless async operation end end end end end
class AppMailer < ApplicationMailer # sends copy of release to current_user def send_release_copy(user_id) @user = User.find(user_id) @company = Company.first mail(to: @user.email, subject: 'Your copy of our release') end # sends notification to user that # admin created a media_file def user_new_mediafile(user_id, media_id) @company = Company.first @user = User.find(user_id) @media_file = MediaFile.find(media_id) @booking = @media_file.booking mail(to: @user.email, subject: 'Media files are ready for your review') end # sends email to admin # when user write a edit note # to a recording/media_files def user_wrote_editnote(user_id, media_id) @company = Company.first @user = User.find(user_id) @media_file = MediaFile.find(media_id) @booking = @media_file.booking mail(to: @company.email, subject: "For admin: #{ @user.full_name} wrote an edit note") # CHANGE @USER.EMAIL TO COMPANY EMAIL OR PRODUCER EMAIL end def admin_approved_with_upload(user_id, media_id) @company = Company.first @user = User.find(user_id) @media_file = MediaFile.find(media_id) @booking = @media_file.booking @media_file.uploads.each_with_index { |file, i| filename = file.id.to_s + file.filename.extension_with_delimiter if ActiveStorage::Blob.service.respond_to?(:path_for) attachments.inline[filename] = File.read(ActiveStorage::Blob.service.send(:path_for, file.key)) elsif ActiveStorage::Blob.service.respond_to?(:download) attachments.inline[filename] = file.download end } mail(to: @user.email, subject: "Your booking media was approved with upload") end def user_approved_media(user_id, media_id) @company = Company.first @user = User.find(user_id) @media_file = MediaFile.find(media_id) @booking = @media_file.booking mail(to: @company.email, subject: "For admin: #{ @user.full_name} approved media") end # email to admin with new booking info # when user creates new booking def new_booking_created(user_id, booking_id) @company = Company.first @user = User.find(user_id) @booking = Booking.find booking_id mail(to: @company.email, subject: "For admin: #{ @user.full_name} just created a booking") end # email to user with new # random generated password def user_new_password(user_id, password) @company = Company.first @user = User.find(user_id) @password = password mail(to: @user.email, subject: "Get a grip studios new password") end end
namespace :legacy do desc "Migrate legacy data to the rails database" task :migrate => :environment do DataMigrator.migrate_all ENV['WORKFILE_PATH'] end end
class ServiceGroup < ApplicationRecord belongs_to :company validates :title, presence: true, length: {maximum: 50, minimum: 5} end
require 'rails_helper' RSpec.describe AddressOrder, type: :model do before do @address_order = FactoryBot.build(:address_order) end describe "商品購入" do context "商品購入がうまくいくとき" do it "建物名が空でも購入できる" do @address_order.building = nil expect(@address_order).to be_valid end it "建物名以外が存在すれば購入できる" do expect(@address_order).to be_valid end it "電話番号はハイフンは不要で、11桁以内だと購入できる" do @address_order.tel = "09012345678" expect(@address_order).to be_valid end end context "商品購入がうまくいかないとき" do it "郵便番号が空だと購入できない" do @address_order.postal_code = nil @address_order.valid? expect(@address_order.errors.full_messages).to include("Postal code is invalid") end it "郵便番号に-を含まないと購入できない" do @address_order.postal_code = "-" @address_order.valid? expect(@address_order.errors.full_messages).to include("Postal code is invalid") end it "都道府県が空だと購入できない" do @address_order.prefecture_id = 1 @address_order.valid? expect(@address_order.errors.full_messages).to include("Prefecture must be other than 1") end it "市区町村が空だと購入できない" do @address_order.municipality = nil @address_order.valid? expect(@address_order.errors.full_messages).to include("Municipality can't be blank") end it "番地が空だと購入できない" do @address_order.address = nil @address_order.valid? expect(@address_order.errors.full_messages).to include("Address can't be blank") end it "電話番号が空だと購入できない" do @address_order.tel = nil @address_order.valid? expect(@address_order.errors.full_messages).to include("Tel can't be blank", "Tel is invalid") end it "電話番号が11桁以上だと購入できない" do @address_order.tel = "123456789123" @address_order.valid? expect(@address_order.errors.full_messages).to include("Tel is invalid") end it "電話番号に-が含まれていると購入できない" do @address_order.tel = "-" @address_order.valid? expect(@address_order.errors.full_messages).to include("Tel is invalid") end end end end