text
stringlengths
10
2.61M
class AddPinToVillageItems < ActiveRecord::Migration def up add_column :village_items, :pin, :string VillageItem.find_each do |vi| vi.update_attribute(:pin, vi.gen_pin) end end def down remove_column :village_items, :pin end end
#---------------------------------------------------------------------------- # Configure #---------------------------------------------------------------------------- if yes?('Would you like to use MySQL? (yes/no)') mysql_flag = true else mysql_flag = false end if yes?('Would you like to use CanCan (yes/no)') cancan_flag = true else cancan_flag = false end if yes?('Would you like to use Devise (yes/no)') devise_flag = true else devise_flag = false end if yes?('Would you like to use Capistrano (yes/no)') capistrano_flag = true else capistrano_flag = false end if yes?('Would you like to use Whenever for Cron (yes/no)') whenever_flag = true else whenever_flag = false end puts "setting up the Gemfile..." run 'rm Gemfile' create_file 'Gemfile', "source 'http://rubygems.org'\n" gem 'rails', '3.2.8' if mysql_flag gem 'mysql2' end gem 'squeel' if cancan_flag gem 'cancan' end if devise_flag gem 'devise' end if whenever_flag gem 'whenever', :require => false end gem 'jquery-rails' inject_into_file "Gemfile", :after => '"jquery-rails"' do <<-RUBY group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', :platforms => :ruby gem 'uglifier', '>= 1.0.3' end group :development do end RUBY end if capistrano_flag inject_into_file "Gemfile", :after => "group :development do\n" do <<-RUBY gem 'capistrano' RUBY end end #---------------------------------------------------------------------------- # Remove the usual cruft #---------------------------------------------------------------------------- run 'rm public/index.html' run 'rm public/favicon.ico' run 'rm app/assets/images/rails.png' run 'rm README' run 'touch README' run 'rm README.rdoc' run 'touch README.rdoc' #---------------------------------------------------------------------------- # If MySQL is being used then create the database.yml file #---------------------------------------------------------------------------- if mysql_flag run 'rm config/database.yml' create_file 'config/database.yml' do <<-FILE login: &login adapter: mysql2 encoding: utf8 reconnect: false pool: 5 username: root password: socket: /var/run/mysqld/mysqld.sock development: database: #{ARGV[0]}_development <<: *login # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: database: #{ARGV[0]}_test mv <<: *login production: database: #{ARGV[0]}_production <<: *login FILE end end # Copy database.yml run 'cp config/database.yml config/database.yml.example' #---------------------------------------------------------------------------- # Set up git #---------------------------------------------------------------------------- run 'rm .gitignore' create_file '.gitignore' do <<-FILE .bundle log/*.log tmp/**/* config/database.yml # bundler state /.bundle vendor/bundle # minimal Rails specific artifacts db/*.sqlite3 /log/* /tmp/* # various artifacts **.war *.rbc *.sassc .rspec .redcar/ .sass-cache /config/config.yml /config/database.yml /coverage.data coverage db/*.javadb /db/*.sqlite3 doc/api doc/app /doc/features.html /doc/specs.html /public/cache /public/stylesheets/compiled /public/system/* /spec/tmp/* /cache /capybara* /capybara-*.html /gems /spec/requests /spec/routing /spec/views /specifications rerun.txt pickle-email-*.html # If you find yourself ignoring temporary files generated by your text editor # or operating system, you probably want to add a global ignore instead: # git config --global core.excludesfile ~/.gitignore_global # # Here are some files you may want to ignore globally: # scm revert files **.orig # Mac finder artifacts .DS_Store # Netbeans project directory .project nbproject # RubyMine project files .idea # Textmate project files /*.tmproj # vim artifacts **.swp FILE end git :init git :add => '.' git :commit => "-m 'Initial commit'"
object @search_result attributes :id,:from_user, :to_user, :about,:message,:msg_type ,:date,:restaurant node(:logo){|m| m.restaurant_logo} node(:icon){|m| m.alert_logo}
class AddVarietyToWines < ActiveRecord::Migration def change add_column :wines, :variety, :string end end
require './src/token' require './src/interpreter/processor' require './spec/contexts/processor' RSpec.describe Interpreter::Processor, 'try' do include_context 'processor' describe '#execute' do it 'catches errors inside try' do mock_lexer( Token.new(Token::TRY), Token.new(Token::SCOPE_BEGIN), Token.new(Token::PARAMETER, '1', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::PARAMETER, '0', particle: 'を', sub_type: Token::VAL_NUM), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::DIVIDE, sub_type: Token::FUNC_BUILT_IN), Token.new(Token::SCOPE_CLOSE), ) expect { execute } .to_not raise_error expect(variable('例外')).to be_truthy end it 'catches calls to throw inside try' do mock_lexer( Token.new(Token::TRY), Token.new(Token::SCOPE_BEGIN), Token.new(Token::PARAMETER, 'hoge', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::THROW, sub_type: Token::FUNC_BUILT_IN), Token.new(Token::SCOPE_CLOSE), ) allow($stderr).to receive(:write) # suppress stderr expect { execute } .to_not raise_error expect(variable('例外')).to eq 'hoge' end it 'clears the error if no error occurs in try' do mock_lexer( Token.new(Token::TRY), Token.new(Token::SCOPE_BEGIN), Token.new(Token::PARAMETER, 'hoge', particle: 'を', sub_type: Token::VAL_STR), Token.new(Token::FUNCTION_CALL, Tokenizer::BuiltIns::THROW, sub_type: Token::FUNC_BUILT_IN), Token.new(Token::SCOPE_CLOSE), Token.new(Token::TRY), Token.new(Token::SCOPE_BEGIN), Token.new(Token::SCOPE_CLOSE), ) allow($stderr).to receive(:write) # suppress stderr expect { execute } .to_not raise_error expect(variable('例外')).to eq nil end end end
# frozen_string_literal: true source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.7.2' gem 'bcrypt' gem 'bootsnap', '>= 1.4.4', require: false gem 'jwt' gem 'pg', '~> 1.1' gem 'puma', '~> 5.0' gem 'rack-cors' gem 'rails', '~> 6.1.4' gem 'rubocop' group :development, :test do gem 'byebug', platforms: %i[mri mingw x64_mingw] gem 'database_cleaner' gem 'factory_bot_rails', '~> 6.1' gem 'faker' gem 'pry-rails', '~> 0.3.4' gem 'rspec-rails', '~> 4.0', '>= 4.0.2' gem 'shoulda-matchers', '~> 4.5', '>= 4.5.1' end group :development do gem 'listen', '~> 3.3' gem 'spring' end gem 'active_model_serializers', '~> 0.10.0' gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] gem 'will_paginate', '~> 3.1.0'
class CreateLocationDates < ActiveRecord::Migration def change if !ActiveRecord::Base.connection.table_exists? 'location_dates' create_table :location_dates do |t| t.string :time_from t.string :time_to t.string :day t.integer :location_id t.timestamps end end end end
require_relative "ruby-uuid" class Jekyll::UUIDGenerator < Jekyll::Generator priority :lowest def generate site base = "" base = site.config["url"] if site.config.has_key? "url" base ||= site.config["uri"] if site.config.has_key? "uri" base ||= site.config["domain"] if site.config.has_key? "domain" base ||= "file://#{site.source}" uri = URI.parse base if uri.scheme.nil? base = "http://#{base}" uri = URI.parse base end site.config["urn"] = if uri.host UUID.create_v5 uri.host.downcase, UUID::NameSpace_DNS else UUID.create_v5 base, UUID::NameSpace_URL end.to_uri unless site.config.has_key? "urn" (site.posts.docs + site.pages).each do |page| next if page.data.has_key? "urn" page.data["urn"] = UUID.create_v5(URI.join(base, page.url).to_s, UUID::NameSpace_URL).to_uri end end end
FactoryBot.define do factory :account, class: Account do association :user account_id { Time.now.to_i } account_name { "Whiskas sache" } balance { 100.0 } end end
require 'combination' describe 'Combination' do let!(:card1) { Card.new('2', 'H') } let!(:card2) { Card.new('3', 'S') } let!(:card3) { Card.new('K', 'C') } let!(:card4) { Card.new('4', 'H') } let!(:card5) { Card.new('7', 'H') } let!(:card6) { Card.new('J', 'C') } let!(:card7) { Card.new('3', 'C') } let!(:card8) { Card.new('5', 'C') } let!(:card9) { Card.new('6', 'C') } let!(:card10) { Card.new('A', 'C') } let!(:card11) { Card.new('2', 'D') } let!(:card12) { Card.new('3', 'D') } let!(:card13) { Card.new('J', 'D') } let!(:deck) { CardStack.new([card1, card2, card3, card4, card5, card6, card7, card8, card9, card10, card11, card12, card13]) } let!(:table) { CardStack.table_on_flop(deck) } let!(:handA) { CardStack.hand(deck) } let!(:handB) { CardStack.hand(deck) } let!(:handC) { CardStack.hand(deck) } let!(:combination1) { Combination.new(handA, table) } let!(:combination2) { Combination.new(handB, table) } let!(:combination3) { Combination.new(handC, table) } describe '#initialize' do it 'create array with 7 cards' do handA = CardStack.new([card1, card2]) table = CardStack.new([card3, card4, card5, card6, card7]) combination = Combination.new(handA, table) expect(combination.cards.count).to eq 7 expect(combination.cards.class).to eq Array expect(combination.cards[0].class).to eq Card end end describe '#high_card' do it 'return highest card in combination' do CardStack.add_card_to_table(table, deck) CardStack.add_card_to_table(table, deck) expect(combination3.high_card).to eq ['high_card', [card6]] end end describe '#pair' do it 'return pair from combination' do CardStack.add_card_to_table(table, deck) CardStack.add_card_to_table(table, deck) expect(combination3.pair).to eq ['pair', [card13, card6]] end end describe '#highest_combination' do context 'when pair in hand + table' do it 'return highest combination from hand + table' do CardStack.add_card_to_table(table, deck) CardStack.add_card_to_table(table, deck) expect(combination3.highest_combination).to eq ['pair', [card13, card6]] end end context 'when nothing in hand + table' do it 'return highest combination from hand + table' do CardStack.add_card_to_table(table, deck) CardStack.add_card_to_table(table, deck) expect(combination1.highest_combination).to eq ['high_card', [card10]] end end describe '.highest_hand' do context 'with only one pair in hands' do it 'compare hands' do CardStack.add_card_to_table(table, deck) CardStack.add_card_to_table(table, deck) h_hand = Combination.highest_hand(combination1, combination2, combination3) expect(h_hand).to eq combination3 end end context 'with two equal combination in hands' do it 'choose with highest card' do card11 = Card.new('K', 'D') CardStack.add_card_to_table(table, deck) CardStack.add_card_to_table(table, deck) h_hand = Combination.highest_hand(combination1, combination2, combination3) expect(h_hand).to eq combination3 end end end end end
class Bicycle attr_reader :size, :parts def initialize(args = {}) @size = args[:size] @parts = args[:parts] end def spares parts.spares end end require 'forwardable' class Part extend Forwardable def_delegators :@parts, :size, :each include Enumerable def initialize(parts) @parts = parts end def spares select { |part| part.needs_spare } end end require 'ostruct' module PartsFactory def self.build(config, parts_class = Parts) parts_class.new( config.collect { |part_config| create_part(part_config) }) end def self.create_part(part_config) OpenStruct.new(name: part_config[0], description: part_config[1], needs_spare: part_config.fetch(2, true)) end end road_config = [['chain', '10-apeed'], ['tire_size', '23'], ['tape_color', 'red']]
module Leagues module Matches module PickBanPermissions extend ActiveSupport::Concern include ::Leagues::MatchPermissions def user_can_submit_pick_ban?(pick_ban = nil) pick_ban ||= @pick_ban if pick_ban.home_team? user_can_home_team? else user_can_away_team? end || user_can_edit_league? end end end end
class Woa::SnippetsController < ApplicationController protect_from_forgery layout 'woa/layouts/wizard_of_awes' include WizardOfAwes.config.helper_auth.to_s.constantize before_filter :woa_authorize def index @snippets = HelperSnippet.all end def new @snippet = HelperSnippet.new end def create @snippet = HelperSnippet.new(params[:helper_snippet]) respond_to do |format| if @snippet.save format.html { redirect_to(woa_snippets_url, :notice => 'Snippet was successfully created.') } format.xml { render :xml => @snippet, :status => :created } else format.html { render :action => "new" } format.xml { render :xml => @snippet.errors, :status => :unprocessable_entity } end end end def edit @snippet = HelperSnippet.find(params[:id]) end def update @snippet = HelperSnippet.find(params[:id]) respond_to do |format| if @snippet.update_attributes(params[:helper_snippet]) format.html { redirect_to(woa_snippets_url, :notice => 'Snippet was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @snippet.errors, :status => :unprocessable_entity } end end end def destroy @snippet = Division.find(params[:id]) @snippet.destroy respond_to do |format| format.html { redirect_to(woa_snippets_url) } format.xml { head :ok } end end end
class PlatformController < ApplicationController before_filter :check_user def check_user authenticate_user! redirect_to root_path unless user_signed_in? end end
require 'fileutils' class FileSystemManager def create_folder(folder_name) unless File.directory?(folder_name) FileUtils.mkdir_p folder_name, :verbose => true end end def delete_folder(path) FileUtils.rm_rf(path) end def create_file(file_name) FileUtils.touch(file_name) end def file_content?(log) file = File.open(log.value, 'rb') content = file.read file.close content end def exec(path, command) if File.directory?(path) FileUtils.cd(path) do system(command) end end end def delete_file_content(path) File.open(path, 'w') {|f| f.truncate(0) } end end
# frozen_string_literal: true require 'aws-sdk-ec2' module AwsClient module EC2 def self.client region = ENV['AWS_EC2_REGION'] || 'ap-northeast-1' profile = ENV['AWS_PROFILE'] || 'default' @client ||= Aws::EC2::Client.new(region: region, profile: profile) end def self.resource @resource ||= Aws::EC2::Resource.new(client: client) end def self.find_instance(name:) instances = client.describe_instances.reservations.map(&:instances).flatten instances.find { |i| i.tags.find { |tag| tag&.key == 'Name' }&.value == name } end def self.create_spot_instance(name:, instance_type: 't4g.nano') tags = [{ key: 'Name', value: name }] tag_resource_types = %w[instance volume network-interface spot-instances-request] tag_specifications = tag_resource_types.map { |type| { resource_type: type, tags: tags } } resource.create_instances({ image_id: 'ami-0427ff21031d224a8', instance_type: instance_type, max_count: 1, min_count: 1, block_device_mappings: [ { device_name: '/dev/xvda', ebs: { delete_on_termination: true, iops: 3000, volume_size: 50, volume_type: 'gp3', throughput: 125 } } ], security_groups: ['public-ssh'], key_name: 'spotcraft-key', instance_initiated_shutdown_behavior: 'stop', tag_specifications: tag_specifications, instance_market_options: { market_type: 'spot', spot_options: { spot_instance_type: 'persistent', instance_interruption_behavior: 'stop' } } }) end def self.create_spot_instance_by_request_spot_instances _res = client.request_spot_instances({ instance_count: 1, launch_specification: { image_id: 'ami-0701e21c502689c31', instance_type: 't3.nano', key_name: 'spot-key-test', placement: { availability_zone: 'ap-northeast-1a' }, security_groups: [ 'public-ssh' ] }, tag_specifications: [ { resource_type: 'spot-instances-request', tags: [ { key: 'Name', value: 'spot-minecraft' } ] } ] }) end end end
class ChangeHolderLength < ActiveRecord::Migration[5.1] def change change_column :categories, :place_holder, :string, limit: 14 end end
require 'set' class WordChainer def initialize(dictionary_file_name) @dictionary = IO.readlines(dictionary_file_name).map{|e|e.chomp!}.to_set end def adjacent_words(word) adjacent_words = [] word.each_char.each_with_index do |old_char, idx| ("a".."z").each do |new_char| next if old_char == new_char new_word = word.dup new_word[idx] = new_char adjacent_words << new_word if @dictionary.include?(new_word) end end adjacent_words end def run(source, target) @current_words = [source] @all_seen_words = {source=>nil} until @current_words.empty? new_current_words = explore_current_words end path = build_path(target) path end def explore_current_words new_current_words = [] @current_words.each do |current_word| adjacents = adjacent_words(current_word) adjacents.each do |adjacent_word| unless @all_seen_words.include?(adjacent_word) new_current_words << adjacent_word @all_seen_words[adjacent_word] = current_word end end @current_words = new_current_words end end def build_path(target) path = [] current_word = target until current_word == nil path << current_word current_word = @all_seen_words[current_word] end path.reverse end end w = WordChainer.new("dictionary.txt") p w.run("duck", "ruby")
class Fluentd module SettingArchive module Archivable extend ActiveSupport::Concern attr_accessor :file_path module ClassMethods private def file_path_of(dir, id) file_path = Pathname.new(dir).join("#{id}#{self::FILE_EXTENSION}") raise "No such a file #{file_path}" unless File.exist?(file_path) file_path end end def file_id @file_id ||= with_file { name.gsub(/#{Regexp.escape(self.class::FILE_EXTENSION)}\Z/,'') } end def name @name ||= with_file { File.basename(file_path) } end def content @content ||= with_file { File.open(file_path, "r") { |f| f.read } } end def ctime with_file { File.ctime(file_path) } end private def with_file return nil unless file_path && File.exist?(file_path) yield end end end end
# # Scopes attributes to be private or protected # # @author [buntekuh] # module ScopedAttrAccessors # # All listed attributes will be privately accessible in the object # @param *names [List of symbols] the attributes to be declared as private # def private_attr_accessor(*names) attr_accessor(*names) names.each do |name| private name private "#{name}=" end end # # All listed attributes will be protected accessible in the object # @param *names [List of symbols] the attributes to be declared as protected # def protected_attr_accessor(*names) protected attr_accessor(*names) end end # # Insert ScopedAttrAccessors into Object # # @author [buntekuh] # class Object extend ScopedAttrAccessors end
require 'rubygems' require 'data_mapper' class User include DataMapper::Resource property :id, Serial property :token, Text, key: true def namespace(key) "#{id}/#{key}" end end
# frozen_string_literal: true class StopsController < ApplicationController def show @stop = Stop.find(params[:stop_id]) end end
class Van DEFAULT_CAPACITY = 6 def initialize(options = {}) @capacity = options.fetch(:capacity, DEFAULT_CAPACITY) @bikes = [] end def full? bike_count == @capacity end def bike_count @bikes.count end def load bike @bikes << bike end end
require 'rails_helper' feature "lessons" do feature "Creating lessons" do background do registered_admin visit(new_lesson_path) end scenario "With invalid information" do expect { click_button "Create Lesson" }.to_not change(Lesson, :count) end scenario "With valid information" do fill_in "Title", with: "Example Title" fill_in "Body", with: "Example" * 10 expect { click_button "Create Lesson" }.to change(Lesson, :count) expect(page).to have_content("Example Title") end end feature "Lesson Completions" do scenario "Is false on creation" do published_lesson expect(page).to have_content("FALSE") end end end
require 'pinocchio/config' require 'pinocchio/environment' require 'pinocchio/vm' require 'pinocchio/version' module Pinocchio def self.config @config = Pinocchio::Config.new do |env| yield env if block_given? end end def self.init @config = Pinocchio::Config.new unless @config @pinocchio = Pinocchio::Environment.new(@config) ENV['VAGRANT_HOME'] = @pinocchio.config.vagrant_home # XXX: placeholder return value? return @pinocchio end end
class Admin::BlogPostsController < ApplicationController before_action :is_admin? def new @blog_post = BlogPost.new end def create @blog_post = BlogPost.new(blog_post_params) if @blog_post.save flash[:notice] = "Blog Post Created!" redirect_to blog_posts_path else flash[:notice] = "An Error Occurred!" redirect to :new end end private def blog_post_params params.require(:blog_post).permit(:title, :body, :user_id) end end
namespace :db do desc "Restore" task :restore => :environment do db_config = ActiveRecord::Base.configurations[::Rails.env] if (db_config['adapter'] = 'postgres') cmd = "pg_restore -U #{db_config['username']} --clean -d #{db_config['database']} < #{ENV['FILE']}" puts "running: #{cmd}" `#{cmd}` else puts "Error: I don't know how to restore using #{db_config['adapter']} adapter" end end end
class TopController < ApplicationController include ApplicationHelper include MovieCategoriesHelper before_action :logged_in_user before_action :movie_schedule_date before_action :progate_comp_date before_action :railstutorial_comp_date before_action :portfolio_comp_path def index # 期限切れでないお知らせ一覧を取得 @information = Information.all.where("display_period >= (?)" , Date.today) @new_movies = Movie.all.where(['created_at > ?', Date.today.prev_day(7)]) # まだ視聴していない視聴必須動画(subject:free)のmovie_category.idを取得 @incomp_category_id = MovieCategory.where(subject: 'free', must_view: true).order(:sort_order) .select { |movie_category| before_category_comp?(movie_category) }.last.id current_user_html = current_user.html_css_status current_user_rubyonrails = current_user.rubyonrails_status current_user_html = current_user.html_css_status current_user_javascript = current_user.javascript_status current_user_ruby = current_user.ruby_status current_user_bootstrap = current_user.bootstrap_status current_user_railstutorial = current_user.railstutorial_status if (current_user_html.ga_beginner && current_user_html.ga_middle && current_user_html.ga_advanced && current_user_html.do_beginner && current_user_html.do_middle && current_user_html.do_advanced && current_user_html.ji_1 && current_user_html.ji_2 && current_user_javascript.ga_1 && current_user_javascript.ga_2 && current_user_javascript.ga_3 && current_user_javascript.ga_4 && current_user_javascript.do_1 && current_user_ruby.ga_1 && current_user_ruby.ga_2 && current_user_ruby.ga_3 && current_user_ruby.ga_4 && current_user_bootstrap.ga_1 && current_user_bootstrap.ga_2 && current_user_ruby.ga_5 &&current_user_rubyonrails.ga_1 && current_user_rubyonrails.ga_2 && current_user_rubyonrails.ga_3 && current_user_rubyonrails.ga_4 && current_user_rubyonrails.ga_5 && current_user_rubyonrails.ga_6 && current_user_rubyonrails.ga_7 && current_user_rubyonrails.ga_8 && current_user_rubyonrails.ga_9 && current_user_rubyonrails.ga_10 && current_user_rubyonrails.ga_11 && current_user_rubyonrails.do_1 && current_user_rubyonrails.do_2 && current_user_rubyonrails.do_3 && current_user_rubyonrails.do_4 && current_user_railstutorial.schedule_date.present?) != true @finish_flag = 1 else @finish_flag = 0 end # [Progate] HTML&CSSのパート current_user_html = current_user.html_css_status if current_user_html.ga_beginner_completion if current_user_html.ga_beginner != true if current_user_html.ga_beginner_completion == Date.today + 3 @ga_beginner_completion = "完了予定日まであと3日です" elsif current_user_html.ga_beginner_completion == Date.today + 2 @ga_beginner_completion = "完了予定日まであと2日です" elsif current_user_html.ga_beginner_completion == Date.today + 1 @ga_beginner_completion = "完了予定日まであと1日です" elsif current_user_html.ga_beginner_completion == Date.today @ga_beginner_completion = "今日が完了予定日です" elsif current_user_html.ga_beginner_completion < Date.today @ga_beginner_completion = "完了予定日を過ぎています" else @ga_beginner_completion = "" end end end current_user_html = current_user.html_css_status if current_user_html.ga_middle_completion if current_user_html.ga_middle != true if current_user_html.ga_middle_completion == Date.today + 3 @ga_middle_completion = "完了予定日まであと3日です" elsif current_user_html.ga_middle_completion == Date.today + 2 @ga_middle_completion = "完了予定日まであと2日です" elsif current_user_html.ga_middle_completion == Date.today + 1 @ga_middle_completion = "完了予定日まであと1日です" elsif current_user_html.ga_middle_completion == Date.today @ga_middle_completion = "今日が完了予定日です" elsif current_user_html.ga_middle_completion < Date.today @ga_middle_completion = "完了予定日を過ぎています" else @ga_middle_completion = "" end end end current_user_html = current_user.html_css_status if current_user_html.ga_advanced_completion if current_user_html.ga_advanced != true if current_user_html.ga_advanced_completion == Date.today + 3 @ga_advanced_completion = "完了予定日まであと3日です" elsif current_user_html.ga_advanced_completion == Date.today + 2 @ga_advanced_completion = "完了予定日まであと2日です" elsif current_user_html.ga_advanced_completion == Date.today + 1 @ga_advanced_completion = "完了予定日まであと1日です" elsif current_user_html.ga_advanced_completion == Date.today @ga_advanced_completion = "今日が完了予定日です" elsif current_user_html.ga_advanced_completion < Date.today @ga_advanced_completion = "完了予定日を過ぎています" else @ga_advanced_completion = "" end end end current_user_html = current_user.html_css_status if current_user_html.do_beginner_completion if current_user_html.do_beginner != true if current_user_html.do_beginner_completion == Date.today + 3 @do_beginner_completion = "完了予定日まであと3日です" elsif current_user_html.do_beginner_completion == Date.today + 2 @do_beginner_completion = "完了予定日まであと2日です" elsif current_user_html.do_beginner_completion == Date.today + 1 @do_beginner_completion = "完了予定日まであと1日です" elsif current_user_html.do_beginner_completion == Date.today @do_beginner_completion = "今日が完了予定日です" elsif current_user_html.do_beginner_completion < Date.today @do_beginner_completion = "完了予定日を過ぎています" else @do_beginner_completion = "" end end end current_user_html = current_user.html_css_status if current_user_html.do_middle_completion if current_user_html.do_middle != true if current_user_html.do_middle_completion == Date.today + 3 @do_middle_completion = "完了予定日まであと3日です" elsif current_user_html.do_middle_completion == Date.today + 2 @do_middle_completion = "完了予定日まであと2日です" elsif current_user_html.do_middle_completion == Date.today + 1 @do_middle_completion = "完了予定日まであと1日です" elsif current_user_html.do_middle_completion == Date.today @do_middle_completion = "今日が完了予定日です" elsif current_user_html.do_middle_completion < Date.today @do_middle_completion = "完了予定日を過ぎています" else @do_middle_completion = "" end end end current_user_html = current_user.html_css_status if current_user_html.do_advanced_completion if current_user_html.do_advanced != true if current_user_html.do_advanced_completion == Date.today + 3 @do_advanced_completion = "完了予定日まであと3日です" elsif current_user_html.do_advanced_completion == Date.today + 2 @do_advanced_completion = "完了予定日まであと2日です" elsif current_user_html.do_advanced_completion == Date.today + 1 @do_advanced_completion = "完了予定日まであと1日です" elsif current_user_html.do_advanced_completion == Date.today @do_advanced_completion = "今日が完了予定日です" elsif current_user_html.do_advanced_completion < Date.today @do_advanced_completion = "完了予定日を過ぎています" else @do_advanced_completion = "" end end end current_user_html = current_user.html_css_status if current_user_html.ji_1_completion if current_user_html.ji_1 != true if current_user_html.ji_1_completion == Date.today + 3 @ji_1_completion = "完了予定日まであと3日です" elsif current_user_html.ji_1_completion == Date.today + 2 @ji_1_completion = "完了予定日まであと2日です" elsif current_user_html.ji_1_completion == Date.today + 1 @ji_1_completion = "完了予定日まであと1日です" elsif current_user_html.ji_1_completion == Date.today @ji_1_completion = "今日が完了予定日です" elsif current_user_html.ji_1_completion < Date.today @ji_1_completion = "完了予定日を過ぎています" else @ji_1_completion = "" end end end current_user_html = current_user.html_css_status if current_user_html.ji_2_completion if current_user_html.ji_2 != true if current_user_html.ji_2_completion == Date.today + 3 @ji_2_completion = "完了予定日まであと3日です" elsif current_user_html.ji_2_completion == Date.today + 2 @ji_2_completion = "完了予定日まであと2日です" elsif current_user_html.ji_2_completion == Date.today + 1 @ji_2_completion = "完了予定日まであと1日です" elsif current_user_html.ji_2_completion == Date.today @ji_2_completion = "今日が完了予定日です" elsif current_user_html.ji_2_completion < Date.today @ji_2_completion = "完了予定日を過ぎています" else @ji_2_completion = "" end end end # [Progate] JavaScriptのパート current_user_javascript = current_user.javascript_status if current_user_javascript.ga_1_completion if current_user_javascript.ga_1 != true if current_user_javascript.ga_1_completion == Date.today + 3 @js_ga_1_completion = "完了予定日まであと3日です" elsif current_user_javascript.ga_1_completion == Date.today + 2 @js_ga_1_completion = "完了予定日まであと2日です" elsif current_user_javascript.ga_1_completion == Date.today + 1 @js_ga_1_completion = "完了予定日まであと1日です" elsif current_user_javascript.ga_1_completion == Date.today @js_ga_1_completion = "今日が完了予定日です" elsif current_user_javascript.ga_1_completion < Date.today @js_ga_1_completion = "完了予定日を過ぎています" else @js_ga_1_completion = "" end end end current_user_javascript = current_user.javascript_status if current_user_javascript.ga_2_completion if current_user_javascript.ga_2 != true if current_user_javascript.ga_2_completion == Date.today + 3 @js_ga_2_completion = "完了予定日まであと3日です" elsif current_user_javascript.ga_2_completion == Date.today + 2 @js_ga_2_completion = "完了予定日まであと2日です" elsif current_user_javascript.ga_2_completion == Date.today + 1 @js_ga_2_completion = "完了予定日まであと1日です" elsif current_user_javascript.ga_2_completion == Date.today @js_ga_2_completion = "今日が完了予定日です" elsif current_user_javascript.ga_2_completion < Date.today @js_ga_2_completion = "完了予定日を過ぎています" else @js_ga_2_completion = "" end end end current_user_javascript = current_user.javascript_status if current_user_javascript.ga_3_completion if current_user_javascript.ga_3 != true if current_user_javascript.ga_3_completion == Date.today + 3 @js_ga_3_completion = "完了予定日まであと3日です" elsif current_user_javascript.ga_3_completion == Date.today + 2 @js_ga_3_completion = "完了予定日まであと2日です" elsif current_user_javascript.ga_3_completion == Date.today + 1 @js_ga_3_completion = "完了予定日まであと1日です" elsif current_user_javascript.ga_3_completion == Date.today @js_ga_3_completion = "今日が完了予定日です" elsif current_user_javascript.ga_3_completion < Date.today @js_ga_3_completion = "完了予定日を過ぎています" else @js_ga_3_completion = "" end end end current_user_javascript = current_user.javascript_status if current_user_javascript.ga_4_completion if current_user_javascript.ga_4 != true if current_user_javascript.ga_4_completion == Date.today + 3 @js_ga_4_completion = "完了予定日まであと3日です" elsif current_user_javascript.ga_4_completion == Date.today + 2 @js_ga_4_completion = "完了予定日まであと2日です" elsif current_user_javascript.ga_4_completion == Date.today + 1 @js_ga_4_completion = "完了予定日まであと1日です" elsif current_user_javascript.ga_4_completion == Date.today @js_ga_4_completion = "今日が完了予定日です" elsif current_user_javascript.ga_4_completion < Date.today @js_ga_4_completion = "完了予定日を過ぎています" else @js_ga_4_completion = "" end end end current_user_javascript = current_user.javascript_status if current_user_javascript.do_1_completion if current_user_javascript.do_1 != true if current_user_javascript.do_1_completion == Date.today + 3 @js_do_1_completion = "完了予定日まであと3日です" elsif current_user_javascript.do_1_completion == Date.today + 2 @js_do_1_completion = "完了予定日まであと2日です" elsif current_user_javascript.do_1_completion == Date.today + 1 @js_do_1_completion = "完了予定日まであと1日です" elsif current_user_javascript.do_1_completion == Date.today @js_do_1_completion = "今日が完了予定日です" elsif current_user_javascript.do_1_completion < Date.today @js_do_1_completion = "完了予定日を過ぎています" else @js_do_1_completion = "" end end end # [Progate] Rubyのパート current_user_ruby = current_user.ruby_status if current_user_ruby.ga_1_completion if current_user_ruby.ga_1 != true if current_user_ruby.ga_1_completion == Date.today + 3 @ruby_ga_1_completion = "完了予定日まであと3日です" elsif current_user_ruby.ga_1_completion == Date.today + 2 @ruby_ga_1_completion = "完了予定日まであと2日です" elsif current_user_ruby.ga_1_completion == Date.today + 1 @ruby_ga_1_completion = "完了予定日まであと1日です" elsif current_user_ruby.ga_1_completion == Date.today @ruby_ga_1_completion = "今日が完了予定日です" elsif current_user_ruby.ga_1_completion < Date.today @ruby_ga_1_completion = "完了予定日を過ぎています" else @ruby_ga_1_completion = "" end end end current_user_ruby = current_user.ruby_status if current_user_ruby.ga_2_completion if current_user_ruby.ga_2 != true if current_user_ruby.ga_2_completion == Date.today + 3 @ruby_ga_2_completion = "完了予定日まであと3日です" elsif current_user_ruby.ga_2_completion == Date.today + 2 @ruby_ga_2_completion = "完了予定日まであと2日です" elsif current_user_ruby.ga_2_completion == Date.today + 1 @ruby_ga_2_completion = "完了予定日まであと1日です" elsif current_user_ruby.ga_2_completion == Date.today @ruby_ga_2_completion = "今日が完了予定日です" elsif current_user_ruby.ga_2_completion < Date.today @ruby_ga_2_completion = "完了予定日を過ぎています" else @ruby_ga_2_completion = "" end end end current_user_ruby = current_user.ruby_status if current_user_ruby.ga_3_completion if current_user_ruby.ga_3 != true if current_user_ruby.ga_3_completion == Date.today + 3 @ruby_ga_3_completion = "完了予定日まであと3日です" elsif current_user_ruby.ga_3_completion == Date.today + 2 @ruby_ga_3_completion = "完了予定日まであと2日です" elsif current_user_ruby.ga_3_completion == Date.today + 1 @ruby_ga_3_completion = "完了予定日まであと1日です" elsif current_user_ruby.ga_3_completion == Date.today @ruby_ga_3_completion = "今日が完了予定日です" elsif current_user_ruby.ga_3_completion < Date.today @ruby_ga_3_completion = "完了予定日を過ぎています" else @ruby_ga_3_completion = "" end end end current_user_ruby = current_user.ruby_status if current_user_ruby.ga_4_completion if current_user_ruby.ga_4 != true if current_user_ruby.ga_4_completion == Date.today + 3 @ruby_ga_4_completion = "完了予定日まであと3日です" elsif current_user_ruby.ga_4_completion == Date.today + 2 @ruby_ga_4_completion = "完了予定日まであと2日です" elsif current_user_ruby.ga_4_completion == Date.today + 1 @ruby_ga_4_completion = "完了予定日まであと1日です" elsif current_user_ruby.ga_4_completion == Date.today @ruby_ga_4_completion = "今日が完了予定日です" elsif current_user_ruby.ga_4_completion < Date.today @ruby_ga_4_completion = "完了予定日を過ぎています" else @ruby_ga_4_completion = "" end end end current_user_ruby = current_user.ruby_status if current_user_ruby.ga_5_completion if current_user_ruby.ga_5 != true if current_user_ruby.ga_5_completion == Date.today + 3 @ruby_ga_5_completion = "完了予定日まであと3日です" elsif current_user_ruby.ga_5_completion == Date.today + 2 @ruby_ga_5_completion = "完了予定日まであと2日です" elsif current_user_ruby.ga_5_completion == Date.today + 1 @ruby_ga_5_completion = "完了予定日まであと1日です" elsif current_user_ruby.ga_5_completion == Date.today @ruby_ga_5_completion = "今日が完了予定日です" elsif current_user_ruby.ga_5_completion < Date.today @ruby_ga_5_completion = "完了予定日を過ぎています" else @ruby_ga_5_completion = "" end end end # [Progate] bootstrapのパート current_user_bootstrap = current_user.bootstrap_status if current_user_bootstrap.ga_1_completion if current_user_bootstrap.ga_1 != true if current_user_bootstrap.ga_1_completion == Date.today + 3 @ruby_ga_1_completion = "完了予定日まであと3日です" elsif current_user_bootstrap.ga_1_completion == Date.today + 2 @ruby_ga_1_completion = "完了予定日まであと2日です" elsif current_user_bootstrap.ga_1_completion == Date.today + 1 @ruby_ga_1_completion = "完了予定日まであと1日です" elsif current_user_bootstrap.ga_1_completion == Date.today @ruby_ga_1_completion = "今日が完了予定日です" elsif current_user_bootstrap.ga_1_completion < Date.today @ruby_ga_1_completion = "完了予定日を過ぎています" else @ruby_ga_1_completion = "" end end end current_user_bootstrap = current_user.bootstrap_status if current_user_bootstrap.ga_2_completion if current_user_bootstrap.ga_2 != true if current_user_bootstrap.ga_2_completion == Date.today + 3 @bootstrap_ga_2_completion = "完了予定日まであと3日です" elsif current_user_bootstrap.ga_2_completion == Date.today + 2 @bootstrap_ga_2_completion = "完了予定日まであと2日です" elsif current_user_bootstrap.ga_2_completion == Date.today + 1 @bootstrap_ga_2_completion = "完了予定日まであと1日です" elsif current_user_bootstrap.ga_2_completion == Date.today @bootstrap_ga_2_completion = "今日が完了予定日です" elsif current_user_bootstrap.ga_2_completion < Date.today @bootstrap_ga_2_completion = "完了予定日を過ぎています" else @bootstrap_ga_2_completion = "" end end end # [Progate] Ruby on Railsのパート current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_1_completion if current_user_rubyonrails.ga_1 != true if current_user_rubyonrails.ga_1_completion == Date.today + 3 @rails_ga_1_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_1_completion == Date.today + 2 @rails_ga_1_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_1_completion == Date.today + 1 @rails_ga_1_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_1_completion == Date.today @rails_ga_1_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_1_completion < Date.today @rails_ga_1_completion = "完了予定日を過ぎています" else @rails_ga_1_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_2_completion if current_user_rubyonrails.ga_2 != true if current_user_rubyonrails.ga_2_completion == Date.today + 3 @rails_ga_2_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_2_completion == Date.today + 2 @rails_ga_2_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_2_completion == Date.today + 1 @rails_ga_2_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_2_completion == Date.today @rails_ga_2_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_2_completion < Date.today @rails_ga_2_completion = "完了予定日を過ぎています" else @rails_ga_2_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_3_completion if current_user_rubyonrails.ga_3 != true if current_user_rubyonrails.ga_3_completion == Date.today + 3 @rails_ga_3_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_3_completion == Date.today + 2 @rails_ga_3_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_3_completion == Date.today + 1 @rails_ga_3_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_3_completion == Date.today @rails_ga_3_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_3_completion < Date.today @rails_ga_3_completion = "完了予定日を過ぎています" else @rails_ga_3_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_4_completion if current_user_rubyonrails.ga_4 != true if current_user_rubyonrails.ga_4_completion == Date.today + 3 @rails_ga_4_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_4_completion == Date.today + 2 @rails_ga_4_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_4_completion == Date.today + 1 @rails_ga_4_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_4_completion == Date.today @rails_ga_4_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_4_completion < Date.today @rails_ga_4_completion = "完了予定日を過ぎています" else @rails_ga_4_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_5_completion if current_user_rubyonrails.ga_5 != true if current_user_rubyonrails.ga_5_completion == Date.today + 3 @rails_ga_5_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_5_completion == Date.today + 2 @rails_ga_5_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_5_completion == Date.today + 1 @rails_ga_5_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_5_completion == Date.today @rails_ga_5_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_5_completion < Date.today @rails_ga_5_completion = "完了予定日を過ぎています" else @rails_ga_5_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_6_completion if current_user_rubyonrails.ga_6 != true if current_user_rubyonrails.ga_6_completion == Date.today + 3 @rails_ga_6_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_6_completion == Date.today + 2 @rails_ga_6_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_6_completion == Date.today + 1 @rails_ga_6_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_6_completion == Date.today @rails_ga_6_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_6_completion < Date.today @rails_ga_6_completion = "完了予定日を過ぎています" else @rails_ga_6_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_7_completion if current_user_rubyonrails.ga_7 != true if current_user_rubyonrails.ga_7_completion == Date.today + 3 @rails_ga_7_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_7_completion == Date.today + 2 @rails_ga_7_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_7_completion == Date.today + 1 @rails_ga_7_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_7_completion == Date.today @rails_ga_7_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_7_completion < Date.today @rails_ga_7_completion = "完了予定日を過ぎています" else @rails_ga_7_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_8_completion if current_user_rubyonrails.ga_8 != true if current_user_rubyonrails.ga_8_completion == Date.today + 3 @rails_ga_8_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_8_completion == Date.today + 2 @rails_ga_8_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_8_completion == Date.today + 1 @rails_ga_8_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_8_completion == Date.today @rails_ga_8_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_8_completion < Date.today @rails_ga_8_completion = "完了予定日を過ぎています" else @rails_ga_8_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_9_completion if current_user_rubyonrails.ga_9 != true if current_user_rubyonrails.ga_9_completion == Date.today + 3 @rails_ga_9_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_9_completion == Date.today + 2 @rails_ga_9_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_9_completion == Date.today + 1 @rails_ga_9_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_9_completion == Date.today @rails_ga_9_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_9_completion < Date.today @rails_ga_9_completion = "完了予定日を過ぎています" else @rails_ga_9_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_10_completion if current_user_rubyonrails.ga_10 != true if current_user_rubyonrails.ga_10_completion == Date.today + 3 @rails_ga_10_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_10_completion == Date.today + 2 @rails_ga_10_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_10_completion == Date.today + 1 @rails_ga_10_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_10_completion == Date.today @rails_ga_10_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_10_completion < Date.today @rails_ga_10_completion = "完了予定日を過ぎています" else @rails_ga_10_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.ga_11_completion if current_user_rubyonrails.ga_11 != true if current_user_rubyonrails.ga_11_completion == Date.today + 3 @rails_ga_11_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.ga_11_completion == Date.today + 2 @rails_ga_11_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.ga_11_completion == Date.today + 1 @rails_ga_11_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.ga_11_completion == Date.today @rails_ga_11_completion = "今日が完了予定日です" elsif current_user_rubyonrails.ga_11_completion < Date.today @rails_ga_11_completion = "完了予定日を過ぎています" else @rails_ga_11_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.do_1_completion if current_user_rubyonrails.do_1 != true if current_user_rubyonrails.do_1_completion == Date.today + 3 @rails_do_1_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.do_1_completion == Date.today + 2 @rails_do_1_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.do_1_completion == Date.today + 1 @rails_do_1_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.do_1_completion == Date.today @rails_do_1_completion = "今日が完了予定日です" elsif current_user_rubyonrails.do_1_completion < Date.today @rails_do_1_completion = "完了予定日を過ぎています" else @rails_do_1_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.do_2_completion if current_user_rubyonrails.do_2 != true if current_user_rubyonrails.do_2_completion == Date.today + 3 @rails_do_2_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.do_2_completion == Date.today + 2 @rails_do_2_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.do_2_completion == Date.today + 1 @rails_do_2_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.do_2_completion == Date.today @rails_do_2_completion = "今日が完了予定日です" elsif current_user_rubyonrails.do_2_completion < Date.today @rails_do_2_completion = "完了予定日を過ぎています" else @rails_do_2_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.do_3_completion if current_user_rubyonrails.do_3 != true if current_user_rubyonrails.do_3_completion == Date.today + 3 @rails_do_3_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.do_3_completion == Date.today + 2 @rails_do_3_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.do_3_completion == Date.today + 1 @rails_do_3_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.do_3_completion == Date.today @rails_do_3_completion = "今日が完了予定日です" elsif current_user_rubyonrails.do_3_completion < Date.today @rails_do_3_completion = "完了予定日を過ぎています" else @rails_do_3_completion = "" end end end current_user_rubyonrails = current_user.rubyonrails_status if current_user_rubyonrails.do_4_completion if current_user_rubyonrails.do_4 != true if current_user_rubyonrails.do_4_completion == Date.today + 3 @rails_do_4_completion = "完了予定日まであと3日です" elsif current_user_rubyonrails.do_4_completion == Date.today + 2 @rails_do_4_completion = "完了予定日まであと2日です" elsif current_user_rubyonrails.do_4_completion == Date.today + 1 @rails_do_4_completion = "完了予定日まであと1日です" elsif current_user_rubyonrails.do_4_completion == Date.today @rails_do_4_completion = "今日が完了予定日です" elsif current_user_rubyonrails.do_4_completion < Date.today @rails_do_4_completion = "完了予定日を過ぎています" else @rails_do_4_completion = "" end end end # Rails Tutorialのパート current_user_railstutorial = current_user.railstutorial_status if current_user_railstutorial.schedule_date if (current_user_railstutorial.chapter1 && current_user_railstutorial.chapter2 && current_user_railstutorial.chapter3 && current_user_railstutorial.chapter4 && current_user_railstutorial.chapter5 && current_user_railstutorial.chapter6 && current_user_railstutorial.chapter7 && current_user_railstutorial.chapter8 && current_user_railstutorial.chapter9 && current_user_railstutorial.chapter10 ) != true if current_user_railstutorial.schedule_date == Date.today + 3 @alert_messages_railstutorial = "完了予定日まであと3日です" elsif current_user_railstutorial.schedule_date == Date.today + 2 @alert_messages_railstutorial = "完了予定日まであと2日です" elsif current_user_railstutorial.schedule_date == Date.today + 1 @alert_messages_railstutorial = "完了予定日まであと1日です" elsif current_user_railstutorial.schedule_date == Date.today @alert_messages_railstutorial = "今日が完了予定日です" elsif current_user_railstutorial.schedule_date < Date.today @alert_messages_railstutorial = "完了予定日を過ぎています" else @alert_messages_railstutorial = "" end end end movie_ids = current_user.feedbacks.pluck(:movie_id) current_user_movie = current_user.user_movie_status if current_user.free_engineer_user && current_user.venture_user last_movie_id = MovieCategory.where(must_view: true).order('sort_order').last.movies.order('sort_order').last.id if current_user_movie.schedule_date if movie_ids.include?(last_movie_id) @alert_message_mv = "" elsif current_user_movie.schedule_date == Date.today + 3 @alert_message_mv = "【完了予定日3日前】" elsif current_user_movie.schedule_date == Date.today + 2 @alert_message_mv = "【完了予定日2日前】" elsif current_user_movie.schedule_date == Date.today + 1 @alert_message_mv = "【完了予定日1日前】" elsif current_user_movie.schedule_date == Date.today @alert_message_mv = "【本日完了予定日】" elsif current_user_movie.schedule_date < Date.today @alert_message_mv = "【完了予定日を過ぎました】" else @alert_message_mv = "" end end elsif current_user.free_engineer_user last_movie_id = MovieCategory.where(must_view: true).where(subject: 'free').order('sort_order').last.movies.order('sort_order').last.id if current_user_movie.schedule_date if movie_ids.include?(last_movie_id) @alert_message_mv = "" elsif current_user_movie.schedule_date == Date.today + 3 @alert_message_mv = "【完了予定日3日前】" elsif current_user_movie.schedule_date == Date.today + 2 @alert_message_mv = "【完了予定日2日前】" elsif current_user_movie.schedule_date == Date.today + 1 @alert_message_mv = "【完了予定日1日前】" elsif current_user_movie.schedule_date == Date.today @alert_message_mv = "【本日完了予定日】" elsif current_user_movie.schedule_date < Date.today @alert_message_mv = "【完了予定日を過ぎました】" else @alert_message_mv = "" end end elsif current_user.venture_user last_movie_id = MovieCategory.where(must_view: true).where(subject: 'venture').order('sort_order').last.movies.order('sort_order').last.id if current_user_movie.schedule_date if movie_ids.include?(last_movie_id) @alert_message_mv = "" elsif current_user_movie.schedule_date == Date.today + 3 @alert_message_mv = "【完了予定日3日前】" elsif current_user_movie.schedule_date == Date.today + 2 @alert_message_mv = "【完了予定日2日前】" elsif current_user_movie.schedule_date == Date.today + 1 @alert_message_mv = "【完了予定日1日前】" elsif current_user_movie.schedule_date == Date.today @alert_message_mv = "【本日完了予定日】" elsif current_user_movie.schedule_date < Date.today @alert_message_mv = "【完了予定日を過ぎました】" else @alert_message_mv = "" end end end end private def set_movie_categories @categories_all = MovieCategory.all.order('sort_order') end def movie_schedule_date link = "<a href=\"#{url_for(current_user)}\"> こちらから</a>" if current_user.user_movie_status.schedule_date.nil? flash.now[:danger] = "動画視聴の完了予定日を入力して下さい#{link}".html_safe end end def progate_comp_date if movie_comp? && progate_completion? flash[:danger] = "プログラミング基礎編の完了予定日を入力して下さい" redirect_to current_user end end def railstutorial_comp_date if progate_compd? && railstutorial_completion? flash[:danger] = "誰でも分かる勤怠システムの完了予定日を入力して下さい" redirect_to current_user end end def portfolio_comp_path # if railstutorial_comp? && portfolio_completion? # flash[:danger] = "ポートフォリオのURLを登録して下さい" # redirect_to edit_user_path(current_user) # end end end
class Admin::GroupBuyOrdersController < Admin::AdminController before_action :set_group_buy include OrderSearch def index @orders = search_orders(params, @group_buy).page(params[:page]) @products = @group_buy.products.sorted end private def set_group_buy @group_buy = GroupBuy.find_by(slug: params[:group_buy_slug]) end end
class HourlyWeathers < ApplicationRecord validates_presence_of :hourly_weather_info has_one :location end
require 'reform' require 'reform/form/dry' module Thing::Contract class Create < Reform::Form include Dry property :name property :description validation do required(:name).filled required(:description).filled end end end
require_relative '../components.rb' #Methods to assist Backup Scripts #Run Backuperator.new_backup to refresh configatron.file_backup_list class Backuperator def initialize configatron.file_backup_list = {} end def self.new_backup Backuperator.new end def add_directory(new_directory) #use absolute paths configatron.file_backup_list[new_directory] = [] unless configatron.file_backup_list.include?(new_directory) end def build_file_lists #Populates Each Added Dir with the Files it Contains configatron.file_backup_list.each_key do |key| Dir.foreach(key){|file| configatron.file_backup_list[key] << file if File.file?("#{key}/#{file}")} end end def add_all_directories(from_this_directory) #check directories with spaces directory_search = `find #{from_this_directory} -type d` directory_list = directory_search.split("\n").to_a directory_list.each{|directory| add_directory(directory)} end def expand_to(backup_directory) setup_logging @backup_directory = File.expand_path(backup_directory) configatron.file_backup_list.each_key do |directory| process_paths directory configatron.file_backup_list[directory].each{|file| execute_copy file} end end private def setup_logging logfile = File.expand_path '~/file_copy/backup.log' FileUtils.rm_r File.expand_path '~/file_copy' if File.exist? logfile FileUtils.mkdir File.expand_path '~/file_copy' @logger = Logger.new(logfile) end def execute_copy file begin FileUtils.cp "#{@directory}/#{file}","#{@backup_directory}#{@base_dir}/#{file}", :preserve => true rescue Errno::ENOENT @logger.error "#{$!} << File Not Copied" rescue Errno::EACCES @logger.error "#{$!} << File Not Copied" end end def process_paths directory @directory = directory @base_dir = directory.dup @base_dir.slice! configatron.user_path new_dir = "#{@backup_directory}/#{@base_dir}" `mkdir -p #{new_dir}` unless File.exists?(new_dir) end end
step "I login with email :email and password :password" do |email, password| visit new_user_session_path fill_in 'Email', :with => email fill_in 'Password', :with => password click_button 'Sign in' page.should have_content("Signed in successfully.") end
class Clinic < ApplicationRecord has_many :arms has_and_belongs_to_many :doctors end
class Song attr_accessor :name, :album attr_reader :id def initialize(collect = {}) @name = collect['name'] @album = collect['album'] @id = collect['id'] end def self.create_table sql = <<-SQL CREATE TABLE IF NOT EXISTS songs ( id INTEGER PRIMARY KEY, name TEXT, album TEXT ) SQL DB[:conn].execute(sql) end def self.all sql = <<-SQL SELECT * FROM songs SQL DB[:conn].execute(sql).collect { |data| self.new(data) } end def save sql = <<-SQL INSERT INTO songs (name, album) VALUES (?, ?); SQL DB[:conn].execute(sql, self.name, self.album) @id = DB[:conn].execute("SELECT * FROM songs").first[0] self end end # class Song # # attr_accessor :name, :album # attr_reader :id # # def initialize(collect = {}) # @name = collect['name'] # @album = collect['album'] # @id = collect['id'] # end # # def self.create_table # # sql = <<-SQL # CREATE TABLE IF NOT EXISTS songs ( # id INTEGER PRIMARY KEY, # name TEXT, # album TEXT ) # SQL # # DB[:conn].execute(sql) # # end # # def self.all # sql = <<-SQL # SELECT * FROM songs # SQL # DB[:conn].execute(sql).collect { |data| self.new(data) } # end # # def save # sql = <<-SQL # INSERT INTO songs (name, album) VALUES (?, ?); # SQL # # DB[:conn].execute(sql, self.name, self.album) # # @id = DB[:conn].execute("SELECT * FROM songs").first[0] # # self # # end # # end
# == Schema Information # # Table name: rooms # # id :integer not null, primary key # joins_count :integer default(0), not null # created_at :datetime not null # updated_at :datetime not null # class Room < ApplicationRecord has_many :joins has_many :users, through: :joins has_one :game, dependent: :destroy scope :joinable, -> { Room.where(joins_count: 0..3).joins('LEFT OUTER JOIN games ON games.room_id = rooms.id').where(games: {room_id: nil}) } def joinable?(user) !(full? || users.exists?(id: user.id) || user.room) end def game_startable?(user) !game && full? && users.exists?(id: user.id) end def full? users.count == 4 end end
class CollectionWork < ApplicationRecord belongs_to :work belongs_to :collection end
class User include Mongoid::Document include Mongoid::Slug # Include default devise modules. Others available are: # :timeoutable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :omniauthable, :lockable ## Database authenticatable field :email, type: String, default: "" field :encrypted_password, type: String, default: "" ## Recoverable field :reset_password_token, type: String field :reset_password_sent_at, type: Time ## Rememberable field :remember_created_at, type: Time ## Trackable field :sign_in_count, type: Integer, default: 0 field :current_sign_in_at, type: Time field :last_sign_in_at, type: Time field :current_sign_in_ip, type: String field :last_sign_in_ip, type: String ## Confirmable field :confirmation_token, type: String field :confirmed_at, type: Time field :confirmation_sent_at, type: Time field :unconfirmed_email, type: String # Only if using reconfirmable ## Lockable field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts field :unlock_token, type: String # Only if unlock strategy is :email or :both field :locked_at, type: Time ## More field :auth_token, type: String field :first_name, type: String field :last_name, type: String field :last_coordinates, type: Array field :time_zone, type: String slug :first_name, :last_name do |doc| [ doc.first_name.delete(' '), doc.last_name.delete(' ') ].compact.join(" ").to_url end ## Association has_many :authentications has_many :societies belongs_to :business belongs_to :privacy embeds_one :privacy_setting accepts_nested_attributes_for :authentications validates :auth_token, uniqueness: true # validates :confirmation_token, uniqueness: true validates :first_name, presence: true validates :last_name, presence: true # before_validation :generate_auth_token! before_create :set_time_zone before_create :set_privacy_setting after_initialize do |user| self.privacy ||= Privacy.find_by(:css => 'web') end def self.authenticate!(email, password) user = User.where(email: email).first return (user.valid_password?(password) ? user : nil) unless user.nil? nil end def generate_token(column) begin self[column] = SecureRandom.hex(64) end while User.find_by(column => self[column]) end def generate_auth_token! begin self.auth_token = SecureRandom.hex(64) end while User.find_by(auth_token: self.auth_token) end def send_password_reset self.generate_token(:reset_password_token) self.reset_password_sent_at = Time.zone.now save! UserMailer.reset_password(self.reset_password_token, self.email, self.first_name, self.last_name).deliver_now end def apply_omniauth(omni) authentications.build(:provider => omni['provider'], :uid => omni['uid'], :token => omni['credentials'].token, :token_secret => omni['credentials'].secret) end class << self def status_with_current_user(from_id, current_user) received_society = Society.find_by(:user_id => from_id, :to_id => current_user.id) if received_society == nil sent_society = Society.find_by(:user_id => current_user.id, :to_id => from_id) if sent_society == nil return {:status => 'add'} else return {:status => 'sent', :id => sent_society.id, :category => sent_society.category} end else if received_society.status == 0 return received_society.category == 0 ? {:status => 'received_friend', :id => received_society.id, :category => received_society.category} : {:status => 'received_business', :id => received_society.id, :category => received_society.category} else return received_society.category == 0 ? {:status => 'friend', :id => received_society.id} : {:status => 'business', :id => received_society.id} end end end def check_save(user) if user.save user else nil end end def auth(omni, last_coordinates) omni['provider'] == 'facebook' ? @token = omni['credentials'].token : @token = omni['credentials'].refresh_token last_name = omni['info'].last_name first_name = omni['info'].first_name email = omni['info'].email user = User.find_by(:email => email) if user.present? authentication = Authentication.find_by(:provider => omni['provider'],:uid => omni['uid']) if authentication.present? user else user.apply_omniauth(omni) check_save(user) end else password = Devise.friendly_token[0,20] user = User.new(:last_name => last_name,:first_name => first_name, :email => email, :password => password) user.last_coordinates = last_coordinates user.skip_confirmation! user.generate_token(:auth_token) user.apply_omniauth(omni) check_save(user) end end end private def set_time_zone timezone = Timezone.lookup(self.last_coordinates[1], self.last_coordinates[0]) self.time_zone = timezone.zone end def set_privacy_setting self.privacy_setting = PrivacySetting.new() end end
require 'webrat' require 'webrat/core/matchers' require 'sauce' SAUCE = ENV["HUB"].match(/sauce/) Before do |scenario| browser = ENV["BROWSER"] || "firefox" browser_version = ENV["VERSION"] || "3." os = ENV["OS"] || "Windows 2003" host_to_test = ENV["HOST_TO_TEST"] || "http://www.google.com" app_port = ENV["APP_PORT"] == 80 ? "" : ":#{ENV["APP_PORT"]}" # Because Sauce Labs has their own gem that works better against the Sauce severs we want to use that # when we are running against Sauce. Otherwise the good ol' Selenium Client Driver will do if SAUCE @selenium = Sauce::Selenium.new(:browser_url => host_to_test + app_port, :browser => browser, :browser_version => browser_version, :os => os, :job_name => scenario.name) else @selenium = Selenium::Client::Driver.new( :host => ENV["HUB"] || "localhost", :port => 4444, :browser => "*#{browser}", :url => host_to_test, :timeout_in_second => 60) end @selenium.start_new_browser_session end After do |scenario| @selenium.stop if SAUCE end
module Admin class ConfsController < AdminController before_action :set_conf, only: [:show, :edit, :update] def update respond_to do |format| if @conf.update(conf_params) format.html { redirect_to admin_conf_path(@conf), notice: '' } else format.html { render :edit , notice: 'wrong value' } end end end def show end def edit end private # Use callbacks to share common setup or constraints between actions. def set_conf @conf = Conf.first end # Never trust parameters from the scary internet, only allow the white list through. def conf_params params.require(:conf).permit( :total_balance ) end end end
class UserServicesController < ApplicationController # # Make sure user is signed in before creating/destroying relationships # before_action :authenticate_user! # # Checks service for current_user and replaces "check" with "_uncheck" partial via create.js.erb # def create_check # # Check the service for user, check!(service) returns the created @user_service object # # @user_service is needed for rendering _uncheck partial in create_check.js.erb # service_id = params[:user_service][:service_id] # @service = Service.find(service_id) # @user_service = current_user.check!(@service) # # AJAX. Rail automatically calls a JavaScript Embedded Ruby (.js.erb) file with the same name as the action # respond_to do |format| # format.html { redirect_to @service } # format.js # execute create_check.js.erb # end # end # # Update the user_service attributes (done via AJAX/asynchronously) # def update # @user_service = UserService.find(params[:id]) # # Continue if update-attribute is sucessful and relationship type is 'check' # if @user_service.update_attributes(check_params) && @user_service.relationship_type == 'check' # # Notify lender that a new application has been submitted # UserServicesMailer.check_updated(@user_service).deliver # # If the user service is finished, charge the lendee # if params[:user_service][:status] == "complete" # @user_service.charge! # end # end # end # # Unchecks service for current_user and places "_uncheck" with "_check" partial via destroy.js.erb # def destroy_check # # Uncheck the service for user # @service = UserService.find(params[:id]).service # current_user.uncheck!(@service) # # @service will be used for rendering _uncheck partial in destroy_check.js.erb # # AJAX. Rail automatically calls a JavaScript Embedded Ruby (.js.erb) file with the same name as the action # respond_to do |format| # format.html { redirect_to @service } # format.js # execute destroy_check.js.erb # end # end # # Checks service for current_user and replaces "check" with "_uncheck" partial via create.js.erb # def create_pin # # Check the service for user, check!(service) returns the created @user_service object # # @user_service is needed for rendering _uncheck partial in create_pin.js.erb # service_id = params[:user_service][:service_id] # @service = Service.find(service_id) # @user_service = current_user.pin!(@service) # # AJAX. Rail automatically calls a JavaScript Embedded Ruby (.js.erb) file with the same name as the action # respond_to do |format| # format.html { redirect_to @service } # format.js # execute create_pin.js.erb # end # end # # Unchecks service for current_user and places "_uncheck" with "_check" partial via destroy.js.erb # def destroy_pin # # Uncheck the service for user # @service = UserService.find(params[:id]).service # current_user.unpin!(@service) # # @service will be used for rendering _uncheck partial in destroy_pin.js.erb # # AJAX. Rail automatically calls a JavaScript Embedded Ruby (.js.erb) file with the same name as the action # respond_to do |format| # format.html { redirect_to @service } # format.js # execute destroy_pin.js.erb # end # end # private # # Strong parameters for check # def check_params # params.require(:user_service).permit(:date, :address, :city, :state, :zip, :status) # end end
require "aethyr/core/objects/weapon" class Dagger < Weapon def initialize(*args) super @generic = "dagger" info.weapon_type = :dagger info.attack = 5 info.defense = 5 end end
class RubyTSQL::Tds::TdsLoginRequestPacket < RubyTSQL::Tds::TdsPacket subclass_type 10 length_field integer_field :tds_version integer_field :packet_size integer_field :client_version integer_field :client_id integer_field :connection_id bit_field do |field| field.flag :little_endian field.flag :character_set field.enum :float_type, :size => 2 do |enum| enum.value :ieee_754 enum.value :vax enum.value :nd5000 end field.flag :supports_dump_load field.flag :warn_when_changing_database field.flag :database field.flag :lang end bit_field do |field| field.flag :use_tsql field.flag :use_odbc field.flag :trans_boundry field.flag :cache_connect field.enum :user_type, :size => 3 do |enum| enum.value :regular enum.value :server enum.value :remuser enum.value :replication_login end field.flag :integrated_security end end
# frozen_string_literal: true namespace :drug_lookup_tables do desc "Reloads the contents of the drug lookup tables from the csvs" task refresh: :environment do Seed::DrugLookupTablesSeeder.truncate_and_import end end
require "date" class Product attr_accessor :name attr_accessor :price def initialize name @name = name evaluate_price name end def evaluate_price name case name when "rice" @price = 1 when "anchovies" @price = 2 end end def getProduct return @price, @name end def season year_day = Date.today.yday().to_i year = Date.today.year.to_i is_leap_year = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 if is_leap_year && year_day > 60 # if is leap year and date > 28 february year_day = year_day - 1 end if year_day >= 355 || year_day < 81 result = :winter elsif year_day >= 81 && year_day < 173 result = :spring elsif year_day >= 173 && year_day < 266 result = :summer elsif year_day >= 266 && year_day < 355 result = :autumn end return result end end class Fruit < Product @@prices_by_season = { "autumn"=> { "banana"=> 20, "grapes"=> 15, "orange"=> 5 }, "winter"=> { "banana"=> 21, "grapes"=> 15, "orange"=> 5 }, "spring"=> { "banana"=> 20, "grapes"=> 15, "orange"=> 5 }, "summer"=> { "banana"=> 20, "grapes"=> 15, "orange"=> 2 } } def evaluate_price name @price = @@prices_by_season[season.to_s][name] end end class Hous2are < Product def evaluate_price @price = 15 end def discount() if(@price>100) @price-= (@price*5/100) puts "¡Descuento del 5%!" end end end
module Ricer::Plugins::Todo class Done < Ricer::Plugin trigger_is 'todo done' has_usage '<id>' def execute(id) solve_todo_entry(Model::Entry.find(id)) end def solve_todo_entry(entry) return rply(:err_already_done, worker: entry.worker.displayname, id: entry.id) unless entry.done_at.nil? entry.done_at = Time.now entry.worker_id = sender.id entry.save! rply :msg_done, id: entry.id, creator: entry.creator.displayname, worker: entry.worker.displayname, text: entry.text, time: entry.displaytime announce_todo_done(entry) end def announce_todo_done(entry) announce = get_plugin("Todo/Announce") announce.announce_targets do |target| if target != user && target != channel target.localize!.send_privmsg(entry.display_take) end end end end end
require_relative "customer.rb" require "csv" # Build Order Class and instantiate instance variables include readers for all attributes class Order attr_reader :id, :products, :customer, :fulfillment_status VALID_STATUSES = [:pending, :paid, :processing, :shipped, :complete] # Build initialize method to take in parameters with a default fulfillment status. def initialize(id, products, customer, fulfillment_status = :pending) @id = id @products = products @customer = customer # Validate that input was among the included possible statuses. Raise error, otherwise. if !VALID_STATUSES.include?(fulfillment_status) raise ArgumentError.new("Invalid Status") end @fulfillment_status = fulfillment_status end # total instance method calculates the total cost of any order by summing products, then adding tax. def total() total_amount = 0.0 @products.each do |product, price| if @products.empty? total_amount = 0.0 else total_amount += price.to_f end end total_amount = (total_amount * 1.075) return (sprintf("%.2f", total_amount).to_f) end # add_product instance method takes in two arguments to add a product into order collection # as long as the product does not already exist in the collection. def add_product(product_name, product_price) if @products.has_key?(product_name) raise ArgumentError.new("That product already exists in this collection") else @products[product_name] = product_price end end # remove_product instance method remoces a product from a collection ny searching for keys matching given input. def remove_product(product_name) if !@products.has_key?(product_name) raise ArgumentError.new("That product is not in the collection anyway") else @products.delete(product_name) end return @products end # all class method reads full collection of orders from the csv. # Formatted by making products in each order into a hash and pushing each attribute into all_orders def self.all all_orders = [] split_by_item = [] product_hash = {} array_array_orders = CSV.read("data/orders.csv") array_array_orders.each do |order| target_customer = Customer.find(order[2].to_i) split_by_item = order[1].split(";") split_by_item.each do |item| product_split_key = item.split(":") product_hash[product_split_key[0]] = product_split_key[1].to_f end all_orders.push(Order.new(order[0].to_i, product_hash, target_customer, order[3].to_sym)) product_hash = {} end return all_orders end # find class method finds and returns an order given its ID as an input. # calls on all method to format in a searchable way. def self.find(order_num) orders = self.all orders.each do |order| if (order.id == order_num) return order end end return nil end end
class User include DataMapper::Resource property :id, Serial property :city, String property :temperature, String property :mode, String end
#!/usr/bin/env ruby # exec ruby hello.rb def h puts "Hello World" end puts "\nDemo1:" h() #################### def h2(name) puts "Hello #{name.capitalize}" end puts "\nDemo2:" h2("evan") #################### class Dog def initialize(name = "World") @name = name end def say_hi puts "Hi #{@name}!" end def say_bye puts "Bye #{@name}!" end end puts "\nDemo3:" g = Dog.new("WangWang") g.say_hi() g.say_bye() puts Dog.instance_methods(false) puts g.respond_to?("say_hi") #################### puts "\nDemo4:" class XDog attr_accessor :names def initialize(names = "World") @names = names end def say_hi if @names.nil? puts "..." elsif @names.respond_to?("each") @names.each do |name| puts "Hello #{name}!" end else puts "Hello #{@names}!" end end def say_bye if @names.nil? puts "..." elsif @names.respond_to?("join") puts "Goodbye #{@names.join(",")}. Come back soon!" else puts "Goodbye #{@names}. Come back soon!" end end end if __FILE__ == $0 mg = XDog.new mg.say_hi mg.say_bye mg.names = "Zeke" mg.say_hi mg.say_bye mg.names = ["aaa", "bbb", "ccc"] mg.say_hi mg.say_bye mg.names = nil mg.say_hi mg.say_bye end
require 'spec_helper' describe "venues/edit.html.erb" do before(:each) do @venue = assign(:venue, stub_model(Venue, :city => "MyString", :prov_state => "MyString", :country => "MyString", :lat => 1.5, :long => 1.5 )) end it "renders the edit venue form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => venues_path(@venue), :method => "post" do assert_select "input#venue_city", :name => "venue[city]" assert_select "input#venue_prov_state", :name => "venue[prov_state]" assert_select "input#venue_country", :name => "venue[country]" assert_select "input#venue_lat", :name => "venue[lat]" assert_select "input#venue_long", :name => "venue[long]" end end end
module Tokenizer class Lexer module TokenLexers def comma?(chunk) chunk =~ /\A[#{COMMA}]\z/ end def tokenize_comma(_chunk) if Context.inside_assignment?(@stack) && !Context.inside_array?(@stack) @stack.insert @stack.index { |t| t.type == Token::ASSIGNMENT } + 1, Token.new(Token::ARRAY_BEGIN) end if eol? peek_next_chunk_in_seq # eat until peeked EOL token, then discard it loop while whitespace? discard_next_chunk_in_seq! end raise Errors::UnexpectedEof if peek_next_chunk_in_seq.empty? (@stack << Token.new(Token::COMMA)).last end end end end
require "test_helper" class FrontPagesControllerTest < ActionController::TestCase def front_page @front_page ||= front_pages :one end def test_index get :index assert_response :success assert_not_nil assigns(:front_pages) end def test_new get :new assert_response :success end def test_create assert_difference("FrontPage.count") do post :create, front_page: { } end assert_redirected_to front_page_path(assigns(:front_page)) end def test_show get :show, id: front_page assert_response :success end def test_edit get :edit, id: front_page assert_response :success end def test_update put :update, id: front_page, front_page: { } assert_redirected_to front_page_path(assigns(:front_page)) end def test_destroy assert_difference("FrontPage.count", -1) do delete :destroy, id: front_page end assert_redirected_to front_pages_path end end
module Baison class Package < Base attr_accessor :shop_code, :status, :receiver_province, :receiver_city, :receiver_district, :receiver_addr, :receiver_name, :pay_type, :pay_time, :receiver_mobile, :deal_code, :buyer_remark, :buyer_name, :record_time, :order_money, :detail attr_writer :goods_num validates :shop_code, :status, :receiver_province, :receiver_city, :receiver_district, :receiver_addr, :receiver_name, :pay_type, :pay_time, :receiver_mobile, :deal_code, :buyer_name, :record_time, :order_money, :goods_num, :detail, presence: true def attributes { :shop_code => nil, :status => nil, :receiver_province => nil, :receiver_city => nil, :receiver_district => nil, :receiver_addr => nil, :receiver_name => nil, :pay_type => nil, :pay_time => nil, :receiver_mobile => nil, :deal_code => nil, :buyer_remark => nil, :buyer_name => nil, :record_time => nil, :order_money => nil, :goods_num => nil, } end def goods_num detail.sum(&:num) end def save unless valid? return false end self.resource = 'oms.api.order.add' json = self.as_json json.merge!(detail: detail.as_json.to_json.to_s) pp json if ENV.fetch('BAISON_VERBOSE', false) json = self.class.connection.post(self.resource, json) pp json if ENV.fetch('BAISON_VERBOSE', false) unless json["status"] == 1 if json["data"].is_a? Array json["data"].each do |item| errors.add(item, :invalid, :message => [json["message"]]) end end end json["status"] == 1 end end end
# require 'spec_helper' # # describe MajorTopic do # describe '#to_s' do # it "returns the name of the tag" do # mt = Fabricate :major_topic, name: "Foo" # expect(mt.to_s).to eq mt.name # end # end # # context "Class methods" do # describe ':none_topic' do # it 'should return the "None" tag' do # expect(MajorTopic.none_topic).to be_kind_of NoneTopic # end # end # # # describe ':names_for_topics' do # # it "should return an array containing the names of the tags" do # # m1 = Fabricate :major_topic, name: "Foo" # # m2 = Fabricate :major_topic, name: "Bar" # # expect(MajorTopic.names_for_topics(m1, m2)).to eq %w(Foo Bar) # # expect(MajorTopic.names_for_topics([m1, m2])).to eq %w(Foo Bar) # # end # # end # # end # # describe '#subtopics' do # it "adds one or more subtopics" do # mt = Fabricate :major_topic, subtopics: [] # expect( mt.add_subtopics('foo') ) # .to change { mt.subtopics.count}.by(1) # expect { mt.add_subtopics('foo') } # .to change { mt.subtopics.count}.by(0) # end # # it "adds the subtopics to @@none_topic" do # mt = Fabricate :major_topic, subtopics: [] # expect { mt.add_subtopics('foo') } # .to change { MajorTopic.none_topic.subtopics.count}.by(1) # end # end # # end
module GpdbInstances class OwnerController < ApplicationController def update authorize! :edit, gpdb_instance Gpdb::InstanceOwnership.change(current_user, gpdb_instance, new_owner) present gpdb_instance end private def new_owner User.find(params[:owner][:id]) end def gpdb_instance @gpdb_instance ||= GpdbInstance.owned_by(current_user).find(params[:gpdb_instance_id]) end end end
class Product < ApplicationRecord has_many :orders has_many :users, through: :orders def self.user_pref(user) # product = Product.find_by(variety: user.variety, flow: user.flow, scent: user.scent) end # def self.box # if @user.variety == "tampon" && @user.flow == "light" && @user.scent == "scent" then # return "tls" # elsif @user.variety == "tampon" && @user.flow == "medium" && @user.scent == "scent" then # return "tms" # elsif @user.variety == "tampon" && @user.flow == "heavy" && @user.scent == "scent" then # return "ths" # elsif @user.variety == "pad" && @user.flow == "light" && @user.scent == "scent" then # return "pls" # elsif @user.variety == "pad" && @user.flow == "medium" && @user.scent == "scent" then # return "pms" # elsif @user.variety == "pad" && @user.flow == "heavy" && @user.scent == "scent" then # return "phs" # elsif @user.variety == "combo" && @user.flow == "light" && @user.scent == "scent" then # return "cls" # elsif @user.variety == "combo" && @user.flow == "medium" && @user.scent == "scent" then # return "cms" # elsif @user.variety == "combo" && @user.flow == "heavy" && @user.scent == "scent" then # return "chs" # elsif @user.variety == "tampon" && @user.flow == "light" && @user.scent == "unscent" then # return "tlu" # elsif @user.variety == "tampon" && @user.flow == "medium" && @user.scent == "unscent" then # return "tms" # elsif @user.variety == "tampon" && @user.flow == "heavy" && @user.scent == "unscent" then # return "thu" # elsif @user.variety == "pad" && @user.flow == "light" && @user.scent == "unscent" then # return "plu" # elsif @user.variety == "pad" && @user.flow == "medium" && @user.scent == "unscent" then # return "pmu" # elsif @user.variety == "pad" && @user.flow == "heavy" && @user.scent == "unscent" then # return "phu" # elsif @user.variety == "combo" && @user.flow == "light" && @user.scent == "unscent" then # return "clu" # elsif @user.variety == "combo" && @user.flow == "medium" && @user.scent == "unscent" then # return "cmu" # elsif @user.variety == "combo" && @user.flow == "heavy" && @user.scent == "scent" then # return "chu" # else # end # end end
#better program logger $logger_depth = 0 #global variable def log desc, &block prefix = ' '*$logger_depth puts prefix + 'Beginning "' + desc + '"...' $logger_depth = $logger_depth + 1 result = block.call $logger_depth = $logger_depth - 1 #by using the formation similar to coding formation we can see in the output how deep we are. The deeper we are the more is the text being pushed to the center puts prefix + '..."' + desc + '" finished, returning: ' + result.to_s end log 'outer block' do log 'some little block' do log 'teeny-tiny block' do 'lOtS oF lOVe'.downcase end 7 * 3 * 2 end log 'yet another block' do '!doof naidnI evol I'.reverse end '0' == "0" end
class Admin::InfosellResourcesController < Admin::WelcomeController def index @infosell_resources = Infosell::Resource.all end def show @infosell_resource = Infosell::Resource.find(params[:id]) end def new @infosell_resource = Infosell::Resource.new :code => "", :name => "", :kind => "", :description => "" end def create @infosell_resource = Infosell::Resource.new(params[:infosell_resource]) @infosell_resource.save! rescue Infosell::Resource::Invalid render :new end def edit @infosell_resource = Infosell::Resource.find(params[:id]) end def update @infosell_resource = Infosell::Resource.find(params[:id]) relations = AuthorizedUrlInfosellResource.find_all_by_elementary_resource_id(@infosell_resource.code) @infosell_resource.update_attributes!(params[:infosell_resource]) AuthorizedUrlInfosellResource.transaction do relations.each do |relation| relation.update_attribute :elementary_resource_id, @infosell_resource.code end end rescue Infosell::Resource::Invalid render :edit end def destroy @infosell_resource = Infosell::Resource.find(params[:id]) @infosell_resource.destroy end end
class Flavor < ApplicationRecord has_many :coffee_flavors has_many :coffees, :through => :coffee_flavors end
class Remembers < ApplicationMailer default bcc: 'tribo@triboviva.com.br' def producer(producer, offers) @offers = offers @producer = producer @day = Date.tomorrow mail to: producer.email, subject: "Entregas Tribo Viva" end def deliver_coordinator(offer) @offer = offer @deliver_coordinator = offer.deliver_coordinator @purchases = @offer.purchases.by_status(PurchaseStatus::PAID).includes(:orders) @quotes_quantity = offer.purchases.sum('orders.quantity') @day = Date.today mail to: @deliver_coordinator.email, subject: "Lembrete de entrega Tribo Viva" end def buyer(user, offer) @user = user @offer = offer @purchase = offer.purchases.includes(:orders).find_by(user: @user) @day = Date.today mail to: user.email, subject: "Lembrete de coleta Tribo Viva" end end
require 'rubygems' require 'selenium-webdriver' require 'test/unit' require File.join(File.dirname(__FILE__), 'test_data') I18n.enforce_available_locales = false class ProductReview < Test::Unit::TestCase def setup @product_permalink = TestData.get_product_fixtures["fixture_4"]["url"] @selenium = Selenium::WebDriver.for(:firefox) end def teardown @selenium.quit end def test_add_new_review review_form_info = TestData.get_comment_form_values({:name => "Dima"}) review_id = generate_new_product_review(review_form_info) review = @selenium.find_element(:id, review_id) name = review.find_element(:class, "comment-author-metainfo").find_element(:class, "url").text comment = review.find_element(:class, "comment-content").text assert_equal("Dima", name) assert_equal(review_form_info[:comment], comment) parsed_date = DateTime.parse(review.find_element(:class, "comment-author-metainfo").find_element(:class, "commentmetadata").text) assert_equal(Date.today.year, parsed_date.year) assert_equal(Date.today.month, parsed_date.month) assert_equal(Date.today.day, parsed_date.day) end def test_adding_a_duplicate_review review_form_info = TestData.get_comment_form_values generate_new_product_review(review_form_info) sleep 2 generate_new_product_review(review_form_info) error = @selenium.find_element(:id, "error-page").text assert_equal("Duplicate comment detected; it looks as though you\u2019ve already said that!", error) end private def find_element(element, strategy=:css) @selenium.find_element(strategy, element) end def type_text(text, element, strategy=:css) find_element(element, strategy).send_keys(text) end def click(element, strategy=:css) find_element(element, strategy).click end def select_desired_product_on_homepage(permalink) click(".special-item a[href*='#{permalink}'].more-info") end def generate_new_product_review(review) navigate_to_homepage select_desired_product_on_homepage(@product_permalink) fill_out_comment_form(review) get_newly_created_review_id end def fill_out_comment_form(form_info) type_text(form_info[:name], "author", :id) type_text(form_info[:email], "email", :id) type_text(form_info[:url], "url", :id) click("a[title='5']") find_element("comment", :id).clear type_text(form_info[:comment], "comment", :id) click("submit", :id) end def navigate_to_homepage @selenium.get(TestData.get_base_url) end def generate_unique_comment "This is a comment for product and is for #{Time.now.to_i}" end def get_newly_created_review_id @selenium.current_url.split("#").last end end
class Task < ApplicationRecord belongs_to :project def project_attributes=(project) self.project = Project.find_or_create_by(title: project.title) self.project.update(project) end end
# frozen_string_literal: true require 'json' require 'spec_helper' require './lib/anonymizer/helper/json_helper.rb' RSpec.describe '#json_helper' do context 'check if valodator work fine wiht valid and invalid json' do before do @valid_json = '{"zupa": "zupa test", "zupa_array": [{"zupa1": "zupa1"}, {"zupa2": "zupa2"}]}' @invalid_json = 'zupa test' end it 'should be a valid json' do expect(JSONHelper.valid_json?(@valid_json)).to be true end it 'should be a invalid json' do expect(JSONHelper.valid_json?(@invalid_json)).to be false end end end
# frozen_string_literal: true # https://adventofcode.com/2019/day/19 require 'pry' require './boilerplate' require './intcode' require './coordinates' class Drone include Loggable include Flat include Intcode attr_accessor :intcode, :grid, :controller def initialize(input) @intcode = Runner.new(input) @grid = Grid.new @controller = Controller.new(@intcode, logging: false) end def scan(from_x: 0, from_y: 0, to_x: 50, to_y: 50) (from_y...to_y).each do |y| (from_x...to_x).each {|x| data = scan_at(x, y)} end grid end def scan_at(x, y) existing = @grid.at(Coordinate.new(x, y)) return existing unless existing.nil? output = @controller.run(x, y) @grid.add(x, y, {code: output, symbol: output == 1 ? '#'.green : '.'}) end end part 1 do grid = Drone.new(input).scan(to_x: 50, to_y: 50) assert_equal(158, grid.select(:code, 1).length, "num_points_affected") end part 2 do drone = Drone.new(input) current = Flat::Coordinate.new(2, 4) # row 1 and 3 have gaps? found = false square = 99 # -1 to exclude the square we're considering while (!found) at = drone.scan_at(current.x, current.y) # we either found a bottom edge, or we found nothing, if nothing move right, # else move down and check again if at[:code] == 0 current = current.move(Flat::Directions::East) else north_coord = current.move(Flat::Directions::North, square) east_coord = north_coord.move(Flat::Directions::East, square) # valid coordinates if north_coord.x >= 0 && north_coord.y >= 0 && east_coord.x >= 0 && east_coord.y >= 0 north = drone.scan_at(north_coord.x, north_coord.y) east = drone.scan_at(east_coord.x, east_coord.y) if north[:code] == 1 && east[:code] == 1 found = true assert_equal(6191165, (north_coord.x * 10000) + north_coord.y, "solution") end end current = current.move(Flat::Directions::South) end end end
# require 'rails_helper' # # RSpec.describe "addresses/new", type: :view do # before(:each) do # assign(:address, Address.new( # :user => nil, # :name => "MyString", # :address1 => "MyString", # :address2 => "MyString", # :zip_code => "MyString", # :city => "MyString", # :state => "MyString", # :country => "MyString", # :phone => "MyString", # :mobile => "MyString", # :email => "MyString", # :website => "MyString", # :other => "MyText" # )) # end # # it "renders new address form" do # render # # assert_select "form[action=?][method=?]", addresses_path, "post" do # # assert_select "input#address_user_id[name=?]", "address[user_id]" # # assert_select "input#address_name[name=?]", "address[name]" # # assert_select "input#address_address1[name=?]", "address[address1]" # # assert_select "input#address_address2[name=?]", "address[address2]" # # assert_select "input#address_zip_code[name=?]", "address[zip_code]" # # assert_select "input#address_city[name=?]", "address[city]" # # assert_select "input#address_state[name=?]", "address[state]" # # assert_select "input#address_country[name=?]", "address[country]" # # assert_select "input#address_phone[name=?]", "address[phone]" # # assert_select "input#address_mobile[name=?]", "address[mobile]" # # assert_select "input#address_email[name=?]", "address[email]" # # assert_select "input#address_website[name=?]", "address[website]" # # assert_select "textarea#address_other[name=?]", "address[other]" # end # end # end
require 'digest/md5' class User < ActiveRecord::Base belongs_to :mentor, class_name: :User has_many :pupils, class_name: User, foreign_key: :mentor_id has_many :pupilCourses def current_course pupilCourses.last end def status if !accepted_invitation 'ainda não se cadastrou' elsif current_course.startedAt.nil? 'não começou o curso' elsif current_course.finishedAt 'finalizou o curso' else current_course.time_missing end end def gravatar md5 = Digest::MD5.hexdigest(email.strip.downcase) "http://www.gravatar.com/avatar/#{md5}.jpg?s=80&d=mm" end def encrypt_password(password) self.accepted_invitation = true self.salt = BCrypt::Engine.generate_salt self.encrypted_password= encode(password) regenerate_key end def regenerate_key salt = BCrypt::Engine.generate_salt self.api_key = "#{id}__#{salt}" end def match_password(login_password) return false if salt.nil? encrypted_password == encode(login_password) end def self.by_api(api_key) User.where(api_key: api_key).first end private def encode(p) BCrypt::Engine.hash_secret(p, salt) end end
module Attachable extend ActiveSupport::Concern included do has_many_attached :files end def file_links_in_hash files.map.with_object([]) do |file, arr| arr << { id: file.id, name: file.filename.to_s, url: Rails.application.routes.url_helpers.rails_blob_url(file, only_path: true) } end end end
class CreateSeasons < ActiveRecord::Migration def change create_table :seasons do |t| t.integer :series_id, null: false t.string :title, limit: 64, null: false t.string :short_description, limit: 255, null: false t.text :description, null: true t.integer :order, limit: 1, null: false, default: 0 t.timestamps null: false t.datetime :deleted_at, null: true end add_foreign_key :seasons, :series, name: :fk_rails_seasons_series end end
class WishListsController < ApplicationController before_action :authenticate_user! def index @wish_lists = current_user.wish_lists end def create # @product used for javascript on create @wish_list = WishList.find_or_initialize_by(product_id: params[:product_id],user_id: current_user.id) @product = Product.find(params[:product_id]) respond_to do |format| if @wish_list.save @wish_lists = current_user.wish_lists @wishlist_create_msg = 'Added to Wish list.' format.html { redirect_to :back, notice: 'Added to Wish list.' } format.js else format.html { render :back } end end end def destroy # @product used for javascript on destroy # @wish_lists used for javascript on destroy to find count @wish_list = WishList.find(params[:id]) @product = Product.find_by(id: @wish_list.product_id) @wish_list.destroy @wish_lists = current_user.wish_lists @wishlist_delete_msg = 'Product removed from wishlist successfully' respond_to do |format| format.html { redirect_to :back, notice: 'Product removed from wishlist successfully' } format.js end end end
class LikesController < ApplicationController before_action :set_variables, only: [:create, :destroy] def index @prototypes = Prototype.all.page(params[:page]).per(10).order("likes_count DESC") end def create @like = Like.create(like_params) end def destroy like = Like.find(params[:id]) like.destroy end private def set_variables @prototype = Prototype.find(params[:prototype_id]) @likes = @prototype.likes end def like_params params.permit(:prototype_id).merge(user_id: current_user.id) end end
require_relative './spec_helper' describe 'backup-script-installed' do describe file('/usr/local/bin/chef-server-backup') do it { should be_file } it { should be_owned_by 'root' } it { should be_executable.by('owner') } end end describe 'backups-configured' do describe file('/etc/chef-server/populator/backup.json') do it { should be_file } it { should be_owned_by 'root' } its(:content) { should match %r{"dir": "/tmp/chef-server/backup"} } its(:content) { should match /"filename": "chef-server-full"/ } it { should be_readable.by('owner') } end end describe 'creates-backups' do describe command('PATH=/opt/chef/embedded/bin:$PATH /usr/local/bin/chef-server-backup') do its(:exit_status) { should eq 0 } end end describe 'creates-cron-job' do describe cron do it { should have_entry '33 3 * * * /usr/local/bin/chef-server-backup' } end end
require_relative '../test_helper' class SourceTest < Minitest::Test def test_it_creates_a_source_with_valid_attributes attributes = {identifier: "jumpstartlab", root_url: "http::/jumpstartlab.com"} source = Source.new(attributes) assert source.valid? source.save assert_equal 1, Source.count end def test_it_does_not_create_source_if_missing_attributes attributes = {identifier: "jumpstartlab"} source = Source.new(attributes) refute source.valid? source.save assert_equal 0, Source.count end def test_it_does_not_create_source_with_non_unique_attribute attributes = {identifier: "jumpstartlab", root_url: "http::/jumpstartlab.com"} source = Source.new(attributes) source2 = Source.new(attributes) assert source.valid? source.save refute source2.valid? source2.save assert_equal 1, Source.count end def setup DatabaseCleaner.start end def teardown DatabaseCleaner.clean end end
class Rectangle def initialize( p1, p2 ) if p1.class != p2.class abort('arguments should have same type') end height, width = case when p1.class == Fixnum || p1.class == Float [ p1, p2 ] when p1.class == Array if !(p1.length == 2 && p2.length == 2) warn 'unknown Rectangle definition' [ 0, 0 ] else [ (p1[0]-p2[0]).abs, (p1[1]-p2[1]).abs ] end else warn 'unknown Rectangle definition' [ 0, 0 ] end @area = height * width @perimeter = 2 * ( height + width ) end def area( round_to = false ) round_to ? self.formatter( @area, round_to ) : @area end def perimeter( round_to = false ) round_to ? self.formatter( @perimeter, round_to ) : @perimeter end def formatter( num, decimals ) multiplier = 1 decimals.times { |i| multiplier *= 10 } ((num *= multiplier ).round.to_f)/multiplier end end if __FILE__ == $0 c1, c2 = [-2], [2,1] r = Rectangle.new( c1, c2 ) puts r.area puts r.perimeter end
class OrderItemsController < ApplicationController def index @order_items = OrderItem.all end def create product = Product.find_by(id: params[:order_item][:product_id]) if session[:order_id].nil? # creates a new order if one doesn't exist @order = Order.create @order_id = @order.id session[:order_id] = @order_id else # uses current order if it exists @order_id = session[:order_id] # @order = Order.find_by(id: session[:order_id]) current_item = @order.order_items.find_by(product_id: order_item_params[:product_id]) # checks if item is already in order, updates by 1 if so if current_item current_item[:qty] += 1 current_item.save flash[:success] = "Successfully updated order item" redirect_to product_path(product.id) return end end if @qty.nil? # set qty to 1 @qty = 1 end if product.stock < 1 || product.status == "Unavailable" flash[:error] = "Could not add item to order (not enough in stock)" redirect_to product_path(product.id) return end order_item = OrderItem.new( order_item_params ) order_item.status = "pending" if order_item.save flash[:success] = "Item added to order" if session[:order_id].nil? session[:order_id] = order_item.order_id end redirect_to product_path(order_item.product_id) else flash[:error] = "Could not add item to order" redirect_to products_path end end def update @order_item = OrderItem.find_by(id: params[:id]) if @order_item.nil? || @order_item.order_id != @order.id flash[:error] = "That order item does not exist" redirect_to root_path return end @product = Product.find_by(id: @order_item.product_id) @order = Order.find_by(id: @order_item.order_id) # removes the item from the order if params[:remove] == "1" if @order_item.destroy flash[:success] = "Successfully removed order item" redirect_to edit_order_path(@order.id) return else flash[:error] = "Could not remove order item" redirect_to root_path return end end # won't let user order fewer than 1 item if params[:quantity].to_i < 1 flash[:error] = "You cannot order fewer than 1" redirect_to edit_order_path(@order.id) return # won't let user order greater than what's in stock elsif params[:quantity].to_i > @product.stock.to_i flash[:error] = "Could not update order (not enough in stock)" redirect_to edit_order_path(@order.id) return end # will let user update qty if @order_item.update(qty: params[:quantity]) flash[:success] = "Successfully updated order item" redirect_to edit_order_path(@order.id) return else flash[:error] = "Could not update order" redirect_to edit_order_path(@order.id) return end end def destroy; end def order_item_params return params.require(:order_item).permit(:product_id, :subtotal).merge(qty: @qty, order_id: @order_id) end end
require 'test_helper' class Dir def self.initialise(r) @tableau = r end def self.entries(*_r) @tableau end end class MaterielsControllerTest < ActionDispatch::IntegrationTest setup do @materiel = materiels(:matos1) end test 'should get index with 2 materials' do get materiels_url assert_response :success assert_select 'div.col-md-4', 2 end test 'should get index with 3 materials' do Materiel.new(nom: 'nom', description: 'desc', photo: 'photo', poids: 1, reforme: false).save get materiels_url assert_response :success assert_select 'div.col-md-4', 3 end test 'new material only accessible to admin' do get new_materiel_url assert_redirected_to materiels_path assert_equal "Vous n'êtes pas administrateur", flash[:notice] end test 'should get new materiel' do post admin_url, params: { password: '51julie2' } Dir.initialise(['0pasdimage.jpg', 'une_autre_photo.jpg', 'encore_une.jpg']) get new_materiel_url assert_response :success assert_select 'option', 2 Dir.initialise(['0pasdimage.jpg', 'une_autre_photo.jpg']) get new_materiel_url assert_response :success assert_select 'option', 1 end test 'should create materiel' do post admin_url, params: { password: '51julie2' } assert_difference('Materiel.count') do post materiels_url, params: { materiel: { nom: 'nom', description: 'desc', photo: 'photo', poids: '1', reforme: false } } end assert_redirected_to materiel_url(Materiel.last) end test 'should show materiel' do get materiel_url(@materiel) assert_response :success assert_select 'h3', 'materiel 1' end test 'non admin should not get edit materiel' do get edit_materiel_url(@materiel) assert_redirected_to @materiel assert_equal "Vous n'êtes pas administrateur", flash[:notice] end test 'admin should get edit materiel' do post admin_url, params: { password: '51julie2' } Dir.initialise(['0pasdimage.jpg', 'une_autre_photo.jpg', 'encore_une.jpg']) get edit_materiel_url(@materiel) assert_response :success end test 'should update materiel' do patch materiel_url(@materiel), params: { materiel: {} } assert_redirected_to materiel_url(@materiel) end test 'non admin should not destroy materiel' do delete materiel_url(@materiel) assert_redirected_to @materiel assert_equal "Vous n'êtes pas administrateur", flash[:notice] end test 'admin should destroy materiel' do post admin_url, params: { password: '51julie2' } assert_difference('Materiel.count', -1) do delete materiel_url(@materiel) end assert_redirected_to materiels_url end end
require 'rails_helper' RSpec.describe UsersController, type: :controller do context 'when user is not logged in' do describe 'GET #new' do it 'returns HTTP success' do get :new expect(response).to have_http_status(:success) end it 'assigns user' do get :new expect(assigns(:user)).not_to be_nil end end describe 'POST #create' do context 'when user is valid' do it 'redirects to the home page' do post :create, user: attributes_for(:user) user = User.order(:created_at).last expect(response).to redirect_to user_companies_path(user) end end context 'when the user is invalid' do it 'fails when name is blank' do post :create, user: attributes_for(:user, name: '') expect(response).to render_template(:new) end it 'fails when last name is blank' do post :create, user: attributes_for(:user, last_name: '') expect(response).to render_template(:new) end it 'fails when email is malformed' do post :create, user: attributes_for(:user, email: 'rafaATgmail.com') expect(response).to render_template(:new) end it 'fails when password is blank' do post :create, user: attributes_for(:user, password: '') expect(response).to render_template(:new) end it 'fails when password is too short' do user = attributes_for(:user, password: 'aaaaaaa', password_confirmation: 'aaaaaaa') post :create, user: user expect(response).to render_template(:new) end it 'fails when password and password confirmation do not match' do user = attributes_for(:user, password: 'aaaaaaaa', password_confirmation: 'bbbbbbbb') post :create, user: user expect(response).to render_template(:new) end end end describe 'GET #show' do it 'does not assign user' do user = create(:user) get :show, id: user.id expect(flash[:danger]).to be == MESSAGES[:auth_error] expect(response).to redirect_to(login_path) end end end context 'when user is logged in' do describe 'GET #new' do it 'redirect to the profile page' do user = create(:user) login_as(user) get :new expect(response).to redirect_to(user_path(user)) end end describe 'GET #show' do it 'assigns user' do user = create(:user) login_as(user) get :show, id: user.id expect(assigns(:user)).not_to be_nil end end end end
file = "rect.rb" begin require_relative file rescue NoMethodError require file end class CellGridView attr_accessor :x, :y, :cell_width, :cell_height attr_accessor :color_alive, :color_dead, :color_revived def initialize(params = Hash.new) @x = params[:x] || 0 @y = params[:y] || 0 @cell_width = params[:cell_width] || 0 @cell_height = params[:cell_height] || 0 @cell_grid = params[:cell_grid] || CellGrid.new @color_alive = params[:color_alive] || 0xff000000 @color_dead = params[:color_dead] || 0xff000000 @color_revived = params[:color_revived] || 0xff000000 @rect = Rect.new(:z_order => params[:z_order] || 0) # maybe needs a test update_rect end def cell_width=(cell_width) @cell_width = cell_width update_rect end def cell_height=(cell_height) @cell_height = cell_height update_rect end def total_width @cell_grid.columns * @cell_width end def total_height @cell_grid.rows * @cell_height end def draw(window) @cell_grid.each_cell_info do |row, column, state| @rect.x = column * @cell_width + @x @rect.y = row * @cell_height + @y case state when CellState::Alive @rect.color = @color_alive when CellState::Dead @rect.color = @color_dead when CellState::Revived @rect.color = @color_revived end @rect.draw(window) end end private def update_rect @rect.width = @cell_width @rect.height = @cell_height end end
require 'quick_cipher/decipher' require 'quick_cipher/encipher' class QuickCipher ALPHABET = ('a'..'z').to_a class << self include Decipher include Encipher end end
class RemoveLastReadFromSubscriptions < ActiveRecord::Migration def up remove_column :subscriptions, :last_read end def down add_column :subscriptions, :last_read, :boolean end end
#!/usr/bin/env ruby require 'open-uri' require 'rexml/document' module Podcast2M3U def self.enclosures(url, restrict=[:http]) url = URI.parse(url) if url.is_a? String raise ArgumentError, "needs a String or a URI" unless url.is_a? URI if !restrict.respond_to?(:include?) && !restrict.is_a?(FalseClass) raise ArgumentError, "restrict must be an Array or FalseClass" end if restrict && !restrict.include?(url.scheme) raise ArgumentError, "URL scheme must be one of #{restrict}" end out = [] open(url.to_s){ |url_f| doc = REXML::Document.new(url_f.read) doc.each_element("//enclosure"){ |el| out << el.attributes["url"] } } out end end if $0==__FILE__ open(ARGV[1], "w"){ |out| Podcast2M3U::enclosures(ARGV[0], false).each{|url| out.puts url } } end
class City < ApplicationRecord belongs_to :pref has_many :city_topics, dependent: :destroy validates :city_name, presence: true, length: { maximum: 50 } end
module Markascend # inline contains the src for fallback Macro = ::Struct.new :env, :content, :inline class Macro def parse name self.content ||= '' if meth = env.macros[name] res = send meth end res or (inline ? ::Markascend.escape_html(inline) : "\\#{name}") end end end
class User < ActiveRecord::Base has_secure_password has_many :event_users has_many :events, through: :event_users has_many :game_users has_many :games, through: :game_users validates :name, presence: true validates :email, presence: true validates :phone_number, presence: true def notify(opponent) @client = Twilio::REST::Client.new ENV['TWILIO_SID'], ENV['TWILIO_AUTH_TOKEN'] @client.account.messages.create({ :from => '+16467833007', :to => self.phone_number, :body => "It is your turn to play Beer Pong!, you will be playing #{opponent.name}", }) end def has_pending_games? games = self.games if games.select{|game| game.status == "pending"}.count > 0 return true else return false end end def games_to_go if self.has_pending_games? @event = self.games.where(status: "pending").last.event p "*" * 10 p @event (@event.games.where(status: "pending").take_while{|game| game.is_player?(self.id) == false}.count) +1 else return false end end end
# frozen_string_literal: true # Abstract class ApplicationRecord < ActiveRecord::Base self.abstract_class = true scope :include_nil, -> { where(status: nil) } scope :not_deleted, -> { where.not(status: 'deleted') } end
module Toolbox module Tools class Help < Base def self.will_handle /^help$/ end def self.help_text "help" end def handle commands = Tools.all.map {|c| c.help_text} commands += [ :logout ] commands.map {|command| "☞ #{command}"}.join("\n") end end end end
class Micropost < ActiveRecord::Base belongs_to :source belongs_to :user has_many :media, dependent: :destroy, inverse_of: :micropost has_many :targets, dependent: :destroy has_many :trollers, dependent: :destroy has_many :troller_clubs, through: :trollers, source: :trollerable, source_type: 'Club' has_many :target_clubs, through: :targets, source: :targetable, source_type: 'Club' validates :provider_id, presence: true validates :shared, presence: true validates :text, presence: true accepts_nested_attributes_for :targets accepts_nested_attributes_for :trollers has_enumeration_for :status, with: MicropostStatus, required: true, create_scopes: true, create_helpers: true default_scope -> { order(updated_at: :desc) } ## # Public: Get only posts based on nickname fan of a club as troller. scope :troller_microposts_from_nick, lambda { |nick| joins(:trollers).where(trollers: { trollerable: nick.club }) } ## # Public: Get only posts based on nickname fan of a club as target. scope :target_microposts_from_nick, lambda { |nick| joins(:targets).where(targets: { targetable: nick.club }) } ## # Public: Get posts based on nickname fans according of your type # (troller/target). scope :versus_microposts_from_nicks, lambda { |troller, target| troller_microposts_from_nick(troller).target_microposts_from_nick(target) } end
class AddGlobalToItemKeys < ActiveRecord::Migration def change add_column :item_keys, :is_global, :boolean add_index :item_keys, :is_global end end
require 'json' class BenchmarkApiController < ApplicationController skip_before_action :verify_authenticity_token before_action :authenticate_request def analyze_no_threads data = { jobs: [], logs: [] } logs = process_jobs(get_jobs(params[:profiles], data)) if logs.empty? render json: { error: "Failed to analyze record(s)" } else render json: logs end end private def profile_params(params) params.permit( :name, :currency, :age, :telephone, :relationship_and_sex, :property_status, :housing_status, :foreign_worker, :job_status, :employment_length, :loan_duration_months, :loan_purpose, :chequing_balance, :loan_amount, :other_debtors_guarantors, :credit_history, :other_loans, :value_of_savings ) end def get_jobs(queries, data) queries.each_with_index do |profile, index| prof = Profile.new(profile_params(profile)) analysis = {id: index, process_date: Time.now, profile: prof} if prof.valid? data[:jobs].push(analysis) else analysis[:verdict] = "Invalid request" data[:logs].push(analysis) end end data end def process_jobs(data) analyzer = Analyzer.new data[:jobs].each do |job| prediction = analyzer. predict(job[:profile].testing_array) job[:verdict] = prediction.first.to_i == 1 ? 'approved' : 'denied' job[:confidence] = "#{(prediction.last.to_f * 100).round(2)}%" data[:logs].push(job) end data[:logs] end end
#draft setup of models create_table "customer", force: true do |t| t.integer "customer_id" t.string "last_name" t.string "first_name" t.string "middle_initial" t.string "street_address_1" t.string "street_address_2" t.string "city" t.string "postal_code" t.string "mobile" t.string "landline" t.integer "dob_month" t.integer "dob_day" t.integer "dob_year" create_table "item", force: true do |t| t.integer "item_id" t.integer "transaction_id" t.string "category" t.string "description" t.string "risk_level" t.string "amount" t.integer "pawn_date" #pawndate t.integer "due_date" #duedate t.string "status" t.history "date" #date create_table "transaction", force: true do |t| t.integer "transaction_id" t.integer "customer_id" t.integer "item_id" t.integer "quantity" t.integer "loan_amount" t.integer "interest" t.integer "service_charge" t.integer "total" t.integer "paid_amount"
class AddActionToEvents < ActiveRecord::Migration[5.1] def change add_column :events, :action, :string, null: false end end
# frozen_string_literal: true # HtmlFile Module module KepplerFrontend module Concerns module RouteFile extend ActiveSupport::Concern def add_route file = "#{url_front}/config/routes.rb" index_html = File.readlines(file) head_idx = 0 index_html.each do |i| head_idx = index_html.find_index(i) if i.include?('KepplerFrontend::Engine.routes.draw do') end if active.eql?(false) index_html.insert(head_idx.to_i + 1, "# #{method.downcase!} '#{url}', to: 'app/frontend##{name}', as: :#{name}\n") else index_html.insert(head_idx.to_i + 1, " #{method.downcase!} '#{url}', to: 'app/frontend##{name}', as: :#{name}\n") end index_html = index_html.join('') File.write(file, index_html) true end def delete_route file = "#{url_front}/config/routes.rb" index_html = File.readlines(file) head_idx = 0 index_html.each do |idx| if active.eql?(false) head_idx = index_html.find_index(idx) if idx.include?("# #{method.downcase} '#{url}', to: 'app/frontend##{name}', as: :#{name}\n") else head_idx = index_html.find_index(idx) if idx.include?(" #{method.downcase} '#{url}', to: 'app/frontend##{name}', as: :#{name}\n") end end return if head_idx==0 index_html.delete_at(head_idx.to_i) index_html = index_html.join('') File.write(file, index_html) true end private def url_front "#{Rails.root}/rockets/keppler_frontend" end end end end
#!/usr/bin/env ruby #encoding: utf-8 module Napakalaki #Enumerado TreasureKind: se encarga de definir un conjunto definido de objetos ONEHAND = :onehand ARMOR = :armor BOTHHANDS = :bothhands HELMET = :helmet SHOE = :shoe NECKLACE = :necklace end
Pod::Spec.new do |s| s.name = "AliCore" s.version ="1.8.5.1" s.description = "阿里百川核心SDK" s.license = { :type => 'Copyright', :text => "Alibaba-INC copyright" } s.author = { "友和" => "lai.zhoul@alibaba-inc.com" } s.source = {:http => "http://baichuan-service-repository.oss-cn-hangzhou.aliyuncs.com/baichuanPlugin/ios/kernel/1.8.5.1/kernel.zip"} s.requires_arc = true s.ios.deployment_target = '6.0' s.platform = :ios s.preserve_paths = "kernel/*.framework/*" s.resources = "kernel/*.bundle" s.vendored_frameworks = 'kernel/*.framework' s.ios.frameworks = 'CoreData', 'SystemConfiguration', 'Security', 'CoreLocation','CoreTelephony','CFNetwork','CoreGraphics' s.libraries ='z' s.xcconfig = { 'OTHER_LDFLAGS' => '-ObjC -lstdc++ -lc++' } end
class AddDonationToPledge < ActiveRecord::Migration def change add_reference :pledges, :donation, index: true, foreign_key: true end end
class AddBodyToEssayStyle < ActiveRecord::Migration def change add_column :essay_styles, :body_id, :integer add_index :essay_styles, :body_id end end
class ApplicationController < ActionController::Base before_action :set_locale # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception protected def log_in(user_name, password) @logged_in_user = User.find_by(user_name: user_name).try(:authenticate, password) session[:user_id] = @logged_in_user.id if @logged_in_user return @logged_in_user end def log_out session[:user_id] = nil end def logged_in_user nil if session[:user_id] @logged_in_user ||= User.find(session[:user_id]) end end helper_method :logged_in_user private def set_locale locale = params[:locale] # Always prefer locale from url if !locale.nil? I18n.locale = locale # Otherwise, if the user has a locale that is not the default locale, # redirect to the same page with the locale parameter prepended. elsif logged_in_user && logged_in_user.locale != I18n.default_locale redirect_to url_for request.params.merge({locale: logged_in_user.locale}) end end end
module MyFacilitiesHelper def preserve_query_params(params, preserve_list) params.select { |param, _| preserve_list.include?(param) } end def percentage(numerator, denominator) return "0%" if denominator.nil? || denominator.zero? || numerator.nil? percentage_string((numerator * 100.0) / denominator) end def opd_load(facility, selected_period) return if facility.monthly_estimated_opd_load.nil? case selected_period when :quarter facility.monthly_estimated_opd_load * 3 when :month facility.monthly_estimated_opd_load end end end
# encoding: utf-8 module Rubocop module Cop module Style # This cop checks for array literals made up of symbols # that are not using the %i() syntax. # # This check makes sense only on Ruby 2.0+. class SymbolArray < Cop MSG = 'Use %i or %I for array of symbols.' def on_array(node) # %i and %I were introduced in Ruby 2.0 unless RUBY_VERSION < '2.0.0' return unless node.loc.begin && node.loc.begin.is?('[') array_elems = node.children # no need to check empty arrays return unless array_elems && array_elems.size > 1 symbol_array = array_elems.all? { |e| e.type == :sym } convention(node, :expression) if symbol_array end end end end end end
module Nyccsc # # This module generates the citaitons in MLA, APA, and Chicago formats. # The document object is passed as a parameter in the citation partial. # This is used in Blacklight as an extension, see solr_document.rb # module Citation # # Generate the mla citation text string # # @param document [Object] Solr document object containing citation display # @return [String] The formatted string for mla citation def export_as_mla_citation_txt(document) citation_field = document['citation_display'][0] citation_object = JSON.parse(citation_field) document_info_object = citation_object['bookCitationInfo'] author_object = citation_object['authorsList'] unless citation_object['authorsList'].nil? author_object = citation_object['editors'] unless citation_object['editors'].nil? authors = get_all_authors(author_object) # Authors author_text = '' if authors[:primary_authors].length < 4 authors[:primary_authors].each_with_index do |author, index| if index == 0 author_text << "#{author}" if authors[:primary_authors].length == 1 author_text << '.' elsif author.ends_with?(',') author_text << ' ' else author_text << ', ' end elsif index + 1 == authors[:primary_authors].length author_text << "and #{name_reverse(author)}." else author_text << "#{name_reverse(author)}, " end end else author_text << authors[:primary_authors].first + ', et al. ' end # Title title = '' title << citation_title(clean_end_punctuation(document_info_object['resourceTitle']).join) # Edition # edition_data = setup_edition(document_info_object) # text += edition_data + " " unless edition_data.nil? # Publisher info and publication date pub_info = '' pub_info << setup_pub_info(document_info_object) pub_info << ", #{setup_pub_date(document_info_object)}" # Citation citation = '' citation << "#{author_text} " unless author_text.blank? citation << "<i>#{title}.</i> " unless title.blank? # citation << "#{edition} " unless edition.blank? citation << "#{pub_info}." unless pub_info.blank? if citation[-1, 1] != '.' citation += '.' unless citation.nil? or citation.blank? end citation end # # Generate the apa citation text string # # @param document [Object] Solr document object containing citation display # @return [String] The formatted string for apa citation def export_as_apa_citation_txt(document) citation_field = document['citation_display'][0] citation_object = JSON.parse(citation_field) document_info_object = citation_object['bookCitationInfo'] author_object = citation_object['authorsList'] unless citation_object['authorsList'].nil? author_object = citation_object['editors'] unless citation_object['editors'].nil? authors_list = [] authors_list_final = [] authors = get_all_authors(author_object) # Authors author_text = '' authors[:primary_authors].each_with_index do |author| authors_list.push(abbreviate_name(author)) unless author.blank? end authors_list.each do |author| if author == authors_list.first # first authors_list_final.push(author.strip) elsif author == authors_list.last # last authors_list_final.push(', &amp; ' + author.strip) else # all others authors_list_final.push(', ' + author.strip) end end author_text << authors_list_final.join unless author_text.blank? if author_text[-1, 1] != '.' author_text += '. ' else author_text += '' end end # Publication Date pub_date = '' pub_date << '(' + setup_pub_date(document_info_object) + '). ' unless setup_pub_date(document_info_object).nil? # Title title = '' title << citation_title(clean_end_punctuation(document_info_object['resourceTitle']).join) # Edition # edition_data = setup_edition(document_info_object) # text += edition_data + " " unless edition_data.nil? # Publisher info pub_info = '' pub_info << setup_pub_info(document_info_object) # Citation citation = '' citation << "#{author_text} " unless author_text.blank? citation << "#{pub_date}" unless pub_date.blank? citation << "<i>#{title}.</i> " unless title.blank? # citation << "#{edition} " unless edition.blank? citation << "#{pub_info}." unless pub_info.blank? unless citation.blank? if citation[-1, 1] != '.' citation += '.' end end citation end # # Generate the chicago citation text string # # @param document [Object] Solr document object containing citation display # @return [String] The formatted string for chicago citation def export_as_chicago_citation_txt(document) citation_field = document['citation_display'][0] citation_object = JSON.parse(citation_field) document_info_object = citation_object['bookCitationInfo'] author_object = citation_object['authorsList'] unless citation_object['authorsList'].nil? author_object = citation_object['editors'] unless citation_object['editors'].nil? authors = get_all_authors(author_object) # Authors author_text = '' unless authors[:primary_authors].blank? if authors[:primary_authors].length > 10 authors[:primary_authors].each_with_index do |author,index| if index < 7 if index == 0 author_text << "#{author}" if author.ends_with?(',') author_text << ' ' else author_text << ', ' end else author_text << "#{name_reverse(author)}, " end end end author_text << ' et al.' elsif authors[:primary_authors].length > 1 authors[:primary_authors].each_with_index do |author, index| if index == 0 author_text << "#{author}" if author.ends_with?(',') author_text << ' ' else author_text << ', ' end elsif index + 1 == authors[:primary_authors].length author_text << "and #{name_reverse(author)}." else author_text << "#{name_reverse(author)}, " end end else author_text << authors[:primary_authors].first + '.' end else temp_authors = [] authors[:translators].each do |translator| temp_authors << [translator, 'trans.'] end authors[:editors].each do |editor| temp_authors << [editor, 'ed.'] end authors[:compilers].each do |compiler| temp_authors << [compiler, 'comp.'] end unless temp_authors.blank? if temp_authors.length > 10 temp_authors.each_with_index do |author, index| if index < 7 author_text << "#{author.first} #{author.last} " end end author_text << ' et al.' elsif temp_authors.length > 1 temp_authors.each_with_index do |author, index| if index == 0 author_text << "#{author.first} #{author.last}, " elsif index + 1 == temp_authors.length author_text << "and #{name_reverse(author.first)} #{author.last}" else author_text << "#{name_reverse(author.first)} #{author.last}, " end end else author_text << "#{temp_authors.first.first} #{temp_authors.first.last}" end end end # Title title = '' title << citation_title(clean_end_punctuation(document_info_object['resourceTitle']).join) if !authors[:primary_authors].blank? and (!authors[:translators].blank? or !authors[:editors].blank? or !authors[:compilers].blank?) additional_title << "Translated by #{authors[:translators].collect{|name| name_reverse(name)}.join(" and ")}. " unless authors[:translators].blank? additional_title << "Edited by #{authors[:editors].collect{|name| name_reverse(name)}.join(" and ")}. " unless authors[:editors].blank? additional_title << "Compiled by #{authors[:compilers].collect{|name| name_reverse(name)}.join(" and ")}. " unless authors[:compilers].blank? end # Edition edition = '' # edition << setup_edition(document_info_object) # Publisher info and publication date pub_info = '' pub_info << setup_pub_info(document_info_object) pub_info << ", #{setup_pub_date(document_info_object)}" # Citation citation = '' citation << "#{author_text} " unless author_text.blank? citation << "<i>#{title}.</i> " unless title.blank? # citation << "#{edition} " unless edition.blank? citation << "#{pub_info}." unless pub_info.blank? citation end def get_all_authors(record) primary_authors = [] translators = [] editors = [] compilers = [] unless record.nil? record['lastName'].zip (record['firstName']).flatten.compact.each do |lastName, firstName| primary_authors << lastName + ', ' + firstName end end { :primary_authors => primary_authors, :translators => translators, :editors => editors, :compilers => compilers } end def name_reverse(name) name = clean_end_punctuation(name) return name unless name =~ /,/ temp_name = name.split(', ') temp_name.last + ' ' + temp_name.first end def clean_end_punctuation(text) if ['.', ',', ':', ':', '/'].include? text[-1, 1] return text[0, text.length - 1] end text end # # This method will take in a string and capitalize all of the non-prepositions. # @param title_text [String] Title text of Solr document # # @return [String] Title text with capitalized words except the prepositions def citation_title(title_text) prepositions = %w('a', 'about', 'across', 'an', 'and', 'before', 'but', 'by', 'for', 'it', 'of', 'the', 'to', 'with', 'without') new_text = [] title_text.split(' ').each_with_index do |word,index| if (index == 0 and word != word.upcase) or (word.length > 1 and word != word.upcase and !prepositions.include?(word)) # the split("-") will handle the capitalization of hyphenated words new_text << word.split('-').map!{|w| w.capitalize }.join('-') else new_text << word end end new_text.join(' ') end def setup_edition(record) edition_field = record['?'] if edition_data.nil? or edition_data == '1st ed.' return nil else return edition_data end end def setup_pub_date(record) pub_date = Date.parse(record['publicationDateValue'].join) unless record['publicationDateValue'].nil? pub_date = pub_date.strftime('%Y') unless pub_date.nil? return nil if pub_date.nil? clean_end_punctuation(pub_date) if pub_date end def setup_pub_info(record) text = '' a_pub_info = record['locationName'].join('') unless record['locationName'].nil? b_pub_info = record['publisherName'].join('') unless record['publisherName'].nil? text += a_pub_info unless a_pub_info.nil? if !a_pub_info.nil? and !b_pub_info.nil? text += ': ' end text += b_pub_info.strip unless b_pub_info.nil? return nil if text.strip.blank? clean_end_punctuation(text.strip) end def abbreviate_name(name) name_parts = name.split(', ') first_name_parts = name_parts.last.split(' ') temp_name = name_parts.first + ', ' + first_name_parts.first[0, 1] + '.' first_name_parts.shift temp_name += ' ' + first_name_parts.join(' ') unless first_name_parts.empty? temp_name end end end
#=============================================================================== # ** Chest_Core #------------------------------------------------------------------------------- # Contiene i metodi di collegamento base con il server. #=============================================================================== module Chest_Service # Regola del nome dello scrigno CHEST_REGX = /<mc:[ ]+(.+),(\d+)>/i # stato dello scrigno CHEST_EMPTY = 100 CHEST_FULL = 101 FILLED = 105 NOT_FILLED = 106 PLAYER_SAME = 107 TOKEN_ERROR = 108 DATA_ERROR = 110 NORMAL_CHEST = -2 FAME = 0 INFAME = 1 # Controllo online dello stato (vuoto o pieno) # chest_key: ID dello scrigno # @param [String] chest_key # @return [Integer]: CHEST_FULL, CHEST_EMPTY o DATA_ERROR se errore def self.get_online_state_chest(chest_key) return DATA_ERROR unless $game_system.can_upload? begin response = Online.get(:chest, :check, {:chest => chest_key}) if [CHEST_FULL, CHEST_EMPTY].include?(response.body.to_i) return response.body.to_i else return DATA_ERROR end rescue => error Logger.error(error.class, error.message) return DATA_ERROR end end # Tenta di prendere l'oggetto dallo scrigno online. # @param [String] chest_id ID dello scrigno # @return [Online_Chest] def self.loot_chest(chest_id) open = Online.upload(:chest, :open, {:chest => chest_id}) if open.success? begin Online_Chest.new(open.result) rescue => exception Logger.error(exception.class) Logger.error(exception.message) Online_Chest.new(Online::DATA_ERROR) end else Online_Chest.new(open.error_code) end end # Restituisce le informazioni dell'evento dello scrigno magico. # event_name: nome dell'evento # Restituisce nil se è uno crigno normale # @return [Local_Chest, nil] def self.map_chest_info(event_name) return Local_Chest.new($1, $2.to_i) if event_name =~ CHEST_REGX nil end # Invia un feedback al giocatore che ha messo l'oggetto nello srigno. # type: tipo di feedback (0: fama, 1: infamia) # chest: scrigno che contiene nome e token. Il token è una stringa di # 20 caratteri generata casualmente dal server per fare in modo che # non possa ricevere feedback infiniti. # @param [Integer] type # @param [Online_Chest] chest def self.send_feedback(type, chest) params = { :token => chest.token, :type => type } operation = Online.upload(:chest, :feedback, params) unless operation.success? Logger.warning sprintf('Send Feedback failed. Reason: %d', operation.error_code) end operation.success? end # Richiede al server di aggiungere un oggetto allo scrigno. # item: ogggetto # la risposta viene memorizzata in $game_temp.chest.response, # ed è una delle costanti di risposta # @param [RPG::BaseItem] item # @throws [InternetConnectionException] # @return [Fixnum] def self.request_fill(item) params = { :item_type => get_type(item), :item_id => item.id, :chest => $game_temp.chest.name } fill = Online.upload(:chest, :fill, params) if fill.success? $game_temp.chest.response = fill.result $game_temp.chest.item = item fill.result else $game_temp.chest.response = fill.error_code fill.error_code end end # Ottiene un valore da 1 a 3 a seconda del tipo di oggetto # @param [RPG::BaseItem] item # @return [Integer] def self.get_type(item) case item when RPG::Item; type = 1 when RPG::Weapon; type = 2 when RPG::Armor; type = 3 else type = 0 end type end end