text
stringlengths
10
2.61M
class CreateJudgement attr_reader :params, :evaluation def initialize(params, evaluation) @params = params @evaluation = evaluation end def call return false unless changed? message = create_message EvaluationMessage.create(sent_at: Time.now, message: message, from_system: true, semester: evaluation.semester, sender_user: nil, group: evaluation.group) evaluation.update(params) end def create_message point_request_change = request_change_message(evaluation.point_request_status, params[:point_request_status]) entry_request_change = request_change_message(evaluation.entry_request_status, params[:entry_request_status]) explanation = params[:explanation] || 'nincs megadva' "Pontkérelem státusza: #{point_request_change}, belépőkérelem státusza: \ #{entry_request_change}, indoklás: #{explanation}" end def request_change_message(old_request, new_request) return 'nem változott' if old_request == new_request "#{old_request} -> #{new_request}" end def changed? evaluation.point_request_status != params[:point_request_status] || evaluation.entry_request_status != params[:entry_request_status] end end
require 'csv' class Collection attr_accessor :id, :institution_id, :name, :size_int, :subjects, :places, :metadata, :people, :dates, :digitized_metadata_size_int, :digitized_size_int, :department, :academic_departments, :divisions def initialize(metadata) @metadata = metadata @id = metadata['gfs_id'] @institution_id = metadata['institution'] @department = metadata['department'] @name = metadata['collection'] @digitized_metadata_size_int = metadata['published_digital_records'].to_s.gsub(',', '').to_i @digitized_size_int = metadata['how_many_digitized_versions'].to_s.gsub(',', '').to_i @subjects = metadata['subjects'].to_s.split(/[\,;]/).collect(&:strip).reject(&:blank?).collect(&:downcase) @academic_departments = metadata['academic_department'].to_s.split(/[\;]/).collect(&:strip).reject(&:blank?) @divisions = metadata['division'].to_s.split(/[\,;]/).collect(&:strip).collect {|c| c.gsub("MPLS", "Mathematical, Physical & Life Sciences")}.reject(&:blank?) @places = metadata['places'].to_s.split(/[,;]/).collect(&:strip).reject(&:blank?) @people = metadata['names'].to_s.split(/[,;]/).collect(&:strip).reject(&:blank?) @dates = metadata['dates'] end def [](test) @metadata[test] end def types_of_things @types_of_things ||= begin type_of_thing_names = @metadata['type_of_things'].to_s .split(';').collect(&:strip).reject(&:blank?) .collect(&:downcase) .collect {|type_of_thing_name| TypeOfThing.find(type_of_thing_name) } end end def type_of_thing_names "test" #type_of_things.collect(&:name) end def catalog_url @catalog_url ||= begin catalog_url = @metadata['catalog_url'].to_s.strip catalog_url.blank? ? nil : catalog_url end end def catalog_comments @catalog_comments ||= begin catalog_comments = @metadata['catalog_comments'].to_s.strip catalog_comments.blank? ? nil : catalog_comments end end def size_int @size_int ||= begin metadata_size_int = metadata['size'].to_s.gsub(',', '').to_i computed_data_size = computed_data['count'].to_i [metadata_size_int, computed_data_size].max end end def percentage_digitized if size_int && digitized_metadata_size_int && size_int > 0 && digitized_metadata_size_int > 0 digitized_metadata_size_int.to_f / size_int * 100 end end def self.subjects all.map(&:subjects).flatten.uniq.compact.sort end def self.types_of_things all.map(&:types_of_things).flatten.uniq.compact.map(&:name).sort end private def computed_data Collection.all_computed_data.detect {|collection| collection['item'] == id } || {} end def self.all_computed_data @all_computed_data ||= begin CSV.read("#{Rails.root.join("db", "collections_computed.csv").to_s}", headers: true).collect do |row| row.to_h end end end def self.all @all ||= begin data = CSV.read("#{Rails.root.join("db", "collections.csv").to_s}", headers: true) data[2..-1].collect do |row| self.new(row.to_h) end end end def self.find(id) all.detect {|c| c.id == id } end end
module Fog module Google class SQL class Mock include Fog::Google::Shared def initialize(options) shared_initialize(options[:google_project], GOOGLE_SQL_API_VERSION, GOOGLE_SQL_BASE_URL) end def self.data @data ||= Hash.new do |hash, key| hash[key] = { :backup_runs => {}, :instances => {}, :operations => {}, :ssl_certs => {} } end end def self.reset @data = nil end def data self.class.data[project] end def reset_data self.class.data.delete(project) end def random_operation "operation-#{Fog::Mock.random_numbers(13)}-#{Fog::Mock.random_hex(13)}-#{Fog::Mock.random_hex(8)}" end end end end end
require_relative 'boot' require 'rails/all' require 'net/http' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module DemoApp class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 config.assets.paths << Rails.root.join('vendor', 'assets', 'bower_components') config.assets.precompile += ['vendor/assets/**/*'] config.assets.precompile += %w('app/assets/javascripts/dashboardCtrl.js.erb') config.assets.precompile += %w(*.svg *.woff *.woff2 *.ttf *.otf *.eot *.png *.jpg *.jpeg *.gif) config.assets.initialize_on_precompile = false config.angular_templates.module_name = 'templates' config.angular_templates.inside_paths = ['app/assets'] config.angular_templates.markups = %w(erb) config.angular_templates.extension = 'html' # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :put , :options, :delete] end end end end
class SchedulesController < AuthenticatedController include PdfGeneratable before_action :set_team before_action :set_schedule, only: [:show, :edit, :update, :destroy] before_action :check_director, only: [:new, :create, :edit, :update, :destroy, :notificate_schedule] before_action :set_year_month_params, only: [:index, :new, :edit, :notificate_schedule] def index @monthly_table_view_model = MonthlyTableViewModel.new(HandleMonth.get_day_range_of_month(params), @team).build respond_to do |format| format.html format.pdf { export_pdf(@team.name) } end end # def show # end def new @schedule = @team.schedules.new end def edit end def create @schedule = @team.schedules.new(schedule_params) @schedule.user_id = current_user.id respond_to do |format| if @schedule.save format.html { redirect_to ym_team_schedules_path(@team, year: @schedule.get_year, month: @schedule.get_month), notice: '予定が作成されました' } else format.html { render :new } end end end def update respond_to do |format| if @schedule.update(schedule_params) format.html { redirect_to ym_team_schedules_path(@team, year: @schedule.get_year, month: @schedule.get_month), notice: '予定が更新されました' } else format.html { render :edit } end end end def destroy @schedule.destroy respond_to do |format| format.html { redirect_to ym_team_schedules_path(@team, year: @schedule.get_year, month: @schedule.get_month), notice: '予定が削除されました' } end end def notificate_schedule @monthly_table_view_model = MonthlyTableViewModel.new(HandleMonth.get_day_range_of_month(params), @team).build @team.users.each do |user| begin NotificationMailer.send_schedule(user, @team, @monthly_table_view_model, @current_view_month).deliver rescue => e Rails.logger.error e.message Rails.logger.error e.backtrace.join('\n') raise StandardError end end redirect_to ym_team_schedules_path(@team, year: @current_view_month.year, month: @current_view_month.month), notice: 'スケジュールを送信しました' end private def set_schedule @schedule = Schedule.find(params[:id]) end def set_team @team = Team.find(params[:team_id]) end def schedule_params params.require(:schedule).permit(:scheduled_at, :start_at, :note, :event_name) end def check_director redirect_to team_schedules_path(@team), alert: '権限がありません' unless @team.by_director?(current_user) end def set_year_month_params @current_view_month = HandleMonth.current_month(params.slice(:year, :month)) end # ここはエラークラスを作りたい def export_pdf(filename) raise StandardError unless @team.by_director?(current_user) generate_pdf(filename) end end
module Markascend class Macro %w[del underline sub sup].each do |m| eval <<-RUBY def parse_#{m} "<#{m}>\#{::Markascend.escape_html content}</#{m}>" end RUBY end def parse_img s = ::StringScanner.new content unless src = s.scan(/(\\\ |\S)+/) env.warn "require src for \\img" return end alt = Macro.scan_attr s, 'alt' s.skip /\s+/ href = Macro.scan_attr s, 'href' s.skip /\s+/ if alt2 = Macro.scan_attr(s, 'alt') alt = alt2 end unless s.eos? env.warn "parse error for content of \\img" return end (href = ::Markascend.escape_attr href) if href alt = ::Markascend.escape_attr alt if env.inline_img begin if env.pwd Dir.chdir env.pwd do data = open src, 'rb', &:read end else data = open src, 'rb', &:read end mime = ::Markascend.mime data if env.retina width, height = ::Markascend.img_size data width /= 2.0 height /= 2.0 size_attrs = %Q|width="#{width}" height="#{height}" | end src = "data:#{mime};base64,#{::Base64.strict_encode64 data}" inlined = true rescue env.warn $!.message end end src = ::Markascend.escape_attr src if not inlined img = %Q|<img #{size_attrs}src="#{src}" alt="#{alt}"/>| if href %Q|<a href="#{href}" rel="nofollow">#{img}</a>| else img end end def parse_html if env.sandbox ::Markascend.sanitize content else content end end def parse_slim ::Slim::Template.new(){content}.render env.scope end def parse_csv Macro.generate_csv content, false end def parse_headless_csv Macro.generate_csv content, true end def parse_latex %Q|<code class="latex">#{content}</code>| end def parse_options yaml = ::YAML.load(content) rescue nil if yaml.is_a?(Hash) env.options.merge! yaml else env.warn '\options content should be a yaml hash' end '' end def parse_hi # TODO validate syntax name env.hi = content == 'none' ? nil : content '' end def parse_dot err, out, code = nil ::Open3.popen3 'dot', '-Tpng' do |i, o, e, t| i.puts content i.close err = e.read out = o.read code = t.value.to_i e.close o.close end if code != 0 env.warn err return end width, height = ::Markascend.img_size out if env.retina width /= 2.0 height /= 2.0 end data = ::Base64.strict_encode64 out %Q|<img width="#{width}" height="#{height}" src="data:image/png;base64,#{data}" alt="#{Markascend.escape_attr content}"/>| end def Macro.generate_csv content, headless rows = ::CSV.parse(content) return if rows.empty? table = "<table>" unless headless table << "<thead>" head = rows.shift head.map!{|e| "<th>#{::Markascend.escape_html e}</th>" } table << "<tr>#{head.join}</tr>" table << "</thead>" end table << "<tbody>" rows.each do |row| row.map!{|e| "<td>#{::Markascend.escape_html e}</td>" } table << "<tr>#{row.join}</tr>" end table << "</tbody></table>" end def Macro.scan_attr strscan, attr_name pos = strscan.pos strscan.skip /\s+/ unless strscan.peek(attr_name.size) == attr_name strscan.pos = pos return end strscan.pos += attr_name.size if strscan.scan(/\s*=\s*/) # http://www.w3.org/TR/html5/syntax.html#attributes-0 if v = strscan.scan(/(["']).*?\1/) v[1...-1] else strscan.scan(/\w+/) end else attr_name end end end end
include DataMagic Given(/^I'm a credit card customer and migration is not enabled$/) do visit LoginPage on(LoginPage) do |page| login_data = page.data_for(:non_migration_account) username = login_data['username'] password = login_data['password'] ssoid = login_data['ssoid'] page.login(username, password, ssoid) end end Given(/^Migration is enabled and my platform code is (.+)$/) do | name | visit LoginPage account = case name when 'EOS' then :eos_platform_account when 'ASCM' then :ascm_platform_account when 'COS EOS' then :cos_eos_platform_account #when 'EOS COS' then :eos_cos_platform_account when 'OLB' then :olb_platform_account when 'ASCM EOS' then :ascm_eos_platform_account when 'ASCM COS EOS' then :ascm_cos_eos_platform_account else raise "Unexpected account name: #{name}" end on(LoginPage).login_for_account account end Given(/^Migration is not enabled and my platform code is EOS$/) do #FigNewton.load "qa1.yml" visit LoginPage on(LoginPage).login_for_account :eos_platform_account end When(/^I try to access the "([^"]*)" page within TETRIS$/) do |page| url_suffix = data_for(:tetris_migration_urls)[page.downcase.gsub(" ", "") + "_tetris_url"] url = @browser.url cleaned_url = url.slice(0..(url.index('.com'))) @browser.goto cleaned_url+url_suffix end Then(/^I am directed to the TETRIS "([^"]*)" page$/) do |page| page_url = data_for(:tetris_migration_urls)[page.downcase.gsub(" ", "") + "_tetris_url"] @browser.url.should include page_url end Then(/^I am( not)? redirected to the "([^"]*)" page in Voyager$/) do |not_flag, page| should_redirect_to_voyager = not_flag.nil? platform_url = should_redirect_to_voyager ? "_voyager_url" : "_tetris_url" page_url = data_for(:tetris_migration_urls)[page.downcase.gsub(" ", "") + platform_url] @browser.url.should include page_url end Then(/^I am redirected to the CVV page in Voyager$/) do page_url = data_for(:tetris_migration_urls)['cvv_voyager_url'] @browser.url.should include page_url end Then(/^I am redirected to the oops page in tetris$/) do page_url = data_for(:tetris_migration_urls)['oops_tetris_url'] @browser.url.should include page_url end
require 'rails_helper' feature "Home", type: :feature, js: true do let!(:user) { create :user } scenario 'Verify log in form' do visit(home_index_path) expect(page).to have_content('Entrar') end scenario 'Valid log in', js: true do visit(home_index_path) fill_in('Email', with: 'admin@admin.com') fill_in('Senha', with: '123456') click_on('Entrar') expect(page).to have_content('MARIA BONITA') # expect(page).to have_content('Login efetuado com sucesso') end scenario 'Invalid login' do visit(home_index_path) fill_in('Email', with: 'user@user.com') fill_in('Senha', with: '123456') click_on('Entrar') expect(page).to have_content('Invalido Email ou senha') end end
# -*- coding: utf-8 -*- require_relative 'photo_variant' module Plugin::Photo # 1種類の画像を扱うModel。 # 同じ画像の複数のサイズ、別形式(Photo Variant)を含むことができ、それらを自動的に使い分ける。 class Photo < Diva::Model include Diva::Model::PhotoInterface register :photo, name: Plugin[:photo]._('画像') field.has :variants, [Diva::Model], required: true field.has :original, InnerPhoto field.uri :perma_link, required: true def self.photos @photos ||= TimeLimitedStorage.new(Integer, self) end # URIからPhoto Modelを得る。 # _uri_ がDiva::Modelだった場合はそれを返すので、PhotoかURIかわからないものをPhotoに変換するのに使える。 # サードパーティプラグインはこれを呼ばず、以下のページを参考にすること。 # https://reference.mikutter.hachune.net/model/2016/11/30/photo-model.html def self.[](uri) case uri when Diva::Model uri when URI, Addressable::URI, Diva::URI, String wrapped_uri = Diva::URI(uri) photos[wrapped_uri.to_s.hash] ||= wrap(wrapped_uri) end end # _perma_link_ のURIをもつPhotoが既にある場合、それを返す。 # ない場合は、 _seeds_ の内容を元に作る。 # ==== Args # [seeds] variant情報のEnumerator(後述) # [perma_link:] variantの代表となるパーマリンク # ===== seedsについて # 有限個のHashについて繰り返すEnumeratorで、 _perma_link_ に対応するPhotoがまだ作られていない場合にだけ利用される。 # 各Hashは以下のキーを持つ。 # :name :: そのvariantの名前。Photoの管理上特に利用されないので、重複していても良い(Symbol) # :width :: そのvariantの画像の幅(px) # :height :: そのvariantの画像の高さ(px) # :policy :: オリジナルからどのようにリサイズされたかを示す値(Symbol) # :photo :: そのvariantの画像を示すPhoto Model又は画像のURL # ===== seedsのpolicyキーについて # policyは以下のいずれかの値。 # [:original] オリジナル画像。一つだけ含まれていること。 # [その他] Plugin::Photo::PhotoVariantを参照 def self.generate(seeds, perma_link:) cached = photos[perma_link.to_s.hash] return cached if cached orig, other = seeds.partition{|s| s[:policy] == :original } new(variants: other.map{|s| PhotoVariant.new(s.merge(photo: InnerPhoto[s[:photo]])) }, perma_link: perma_link, original: InnerPhoto[orig.first[:photo]]) end def self.wrap(model_or_uri) inner_photo = InnerPhoto[model_or_uri] new(variants: [], perma_link: inner_photo.perma_link, original: inner_photo) end def initialize(*params) super each_photos do |photo| self.class.photos[photo.uri.to_s.hash] = self end self.class.photos[uri.to_s.hash] = self end # variantが保持している各Photo Modelを引数にしてblockを呼び出す。 # blockを指定しなかった場合は、Enumeratorを返す # ==== Return # [self] ブロックを渡した場合 # [Enumerator] Photo Modelを列挙するEnumerator def each_photos(&block) if block_given? variants.each{|pv| block.(pv.photo) } self else variants.lazy.map(&:photo) end end def download(width: nil, height: nil, &partial_callback) if width && height larger_than(width: width, height: height) .download(width: width, height: height, &partial_callback) else maximum_original.download(width: width, height: height, &partial_callback) end end # PhotoInterfaceをgtkプラグインが拡張し、内部でこのメソッドを呼ぶ。 # このModelでは必要ないため空のメソッドを定義しておく。 def increase_read_count end def blob maximum_original.blob end # 指定された幅と高さを上回るvariantを返す。 # 既に画像がダウンロードされているvariantのうち、最小のものを使う。 # 引数に指定された条件を満たす中で既にダウンロードされている画像がない場合は、条件を満たす最小のvariantを返す。 # ==== Args # [width:] (Integer) # [height:] (Integer) # ==== Return # [Photo Model] 最適なPhoto Model def larger_than(width:, height:) largers = variants.select{|pv| pv.policy.to_sym == :fit && pv.width >= width && pv.height >= height }.sort_by(&:width) if largers.empty? maximum_original else (largers.find{|pv| pv.photo.completed? } || largers.first).photo end end # 最大サイズのPhotoを返す。 # originalがあればそれを返すが、なければfit policyのvariantのうち最大のものを返す。 # ==== Return # [Photo Model] 最大のPhoto def maximum self.class.wrap(maximum_original) end private def maximum_original if original original else variant = variants.find{|v| v.policy.to_sym == :fit } if variant variant.photo else variants.sample.photo end end end end end
require "rails_helper" feature "patient search returns list of patients", type: :feature do let!(:john) { FactoryBot.create(:patient, first_name: "John", last_name: "Doe") } let!(:jane) { FactoryBot.create(:patient, first_name: "Jane", last_name: "Doe") } let!(:freddie) { FactoryBot.create(:patient, first_name: "Freddy", last_name: "Mercury") } background do visit patients_path end scenario "user does not query search" do expect(page).to have_content("All Patients") expect(page).to have_content("Antoine") expect(page).to_not have_content("Liang") end scenario "user enters search query" do visit "/patients?search=#{john.last_name}" expect(page).to have_content("All patients whose names include") expect(page).to have_content(john.first_name) expect(page).to have_content(jane.first_name) expect(page).to_not have_content(freddie.first_name) end end
class Item # To access in these variable from Receipt class attr_accessor :name, :price, :sales_taxes, :import_taxes def initialize(name, price, sales_taxes, import_taxes) @name = name @price = price @sales_taxes = sales_taxes @import_taxes = import_taxes end end
require "pry" require "yaml" MESSAGES = YAML.load_file('messages.yml') def calculator(x,y,operation) if x.to_i.integer? x = x.to_i else "Please input a valid integer for x" end if y.to_i.integer? y = y.to_i else "Please input a valid integer for y" end if operation == "+" "The answer is #{x+y}!" elsif operation == "-" "The answer is #{x-y}!" elsif operation == "*" "The answer is #{x*y}!" elsif operation == "/" "The answer is #{x.to_f/y.to_f}!" else "Please input a valid operator. Choices are '+,-,* or /" end end loop do puts "I am your calculator! Please give me two integers, and then tell me which operation you would like performed (+,-,* or /)" x = gets().chomp() y = gets().chomp() operation = gets().chomp() puts calculator(x,y,operation) puts "Would you like to continue? Y/N" break if gets().chomp().downcase()=="n" end
class V1::PerformerResource < JSONAPI::Resource attributes :instrument has_one :person has_one :song end
DevToolsApp::Application.routes.draw do root 'tools#index' get 'login' => 'auths#new' delete 'logout' => 'auths#destroy' get 'tools/list', :to => "tools#list" resources :users, only: [:index, :show, :create, :new] resources :tools, only: [:index, :show, :create, :new, :edit, :update, :destroy] resources :categories, only: [:index, :show, :create, :new, :edit, :update, :destroy] resource :auth, only: [:create] end
require 'rspec/core/rake_task' default_opts = ['--format progress', '--color'] namespace :spec do desc "Run all specs" RSpec::Core::RakeTask.new(:all) do |t| t.rspec_opts = [*default_opts] end desc "Run all specs that should pass" RSpec::Core::RakeTask.new(:ok) do |t| t.rspec_opts = [*default_opts, '--tag ~wip'] end desc "Run specs that are being worked on" RSpec::Core::RakeTask.new(:wip) do |t| t.rspec_opts = [*default_opts, '--tag wip'] end desc "Run all specs and show the ten slowest examples" RSpec::Core::RakeTask.new(:profile) do |t| t.rspec_opts = [*default_opts, '--profile', '--tag ~wip'] end end desc "Alias for spec:ok" task spec: 'spec:ok'
class CreateGermanArticles < ActiveRecord::Migration def change Article.transaction do Article.all.each do |legacy_article| legacy_article.article_tags.each_with_index do |article_tag, index| position = index + 1 legacy_article.article_tag_positions.create!({ tag: article_tag.tag, position: position }) end article_attributes = { article: legacy_article, created_at: legacy_article.created_at, updated_at: legacy_article.updated_at } english_article = TranslatedArticle.new article_attributes english_article.locale = :en english_article.title = legacy_article.title_en english_article.text = legacy_article.content_en english_article.summary = legacy_article.summary_en english_article.slug = legacy_article.slug german_article = TranslatedArticle.new article_attributes german_article.locale = :de german_article.title = legacy_article.title_de german_article.text = legacy_article.content_de german_article.summary = legacy_article.summary_de german_article.slug = nil english_article.save! german_article.save! end end end end
# # Cookbook Name:: nodejs # Recipe:: default # # Copyright 2014, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # def install_nodejs(source, file, build_dir, prefix, flags) remote_file "#{Chef::Config[:file_cache_path]}/#{file}" do source source mode "0644" action :create_if_missing not_if "test -e #{prefix}/bin/node" end bash "install-nodejs #{build_dir}" do user "root" cwd Chef::Config[:file_cache_path] code <<-EOH set -e tar -xf #{file} cd #{build_dir} ./configure --prefix=#{prefix} #{flags} make make install EOH not_if "test -e #{prefix}/bin/node" end end install_nodejs( 'http://nodejs.org/dist/v0.10.24/node-v0.10.24.tar.gz', 'node-v0.10.24.tar.gz', 'node-v0.10.24', '/usr/local/node-0.10.24', '')
json.array!(@pagecounts) do |pagecount| json.extract! pagecount, :pageview json.url pagecount_url(pagecount, format: :json) end
class DeliveryCenter::Deploy < DeliveryCenter::ApplicationRecord belongs_to :application, class_name: 'DeliveryCenter::Application' belongs_to :revision, class_name: 'DeliveryCenter::Revision' def mark_current! self.class.transaction do self.class.where(application_id: application_id).update_all(current: false) self.current = true self.save! end end end
require 'rails_helper' RSpec.describe UsersController, type: :controller do describe "GET show" do it "returns http status success" do user = create(:user) sign_in user get :show expect(response).to have_http_status(:success) end end end
require 'rails_helper' RSpec.describe FileParser::CSVParser do let(:csv_file) { fixture_file_upload(Rails.root.join('spec', 'support', 'files', 'command_file.csv'), 'text/csv') } describe '#parse_data' do specify do expect(FileParser::CSVParser.new(csv_file).parse_data) .to eq(['PLACE 1,2,EAST', 'MOVE', 'MOVE', 'LEFT', 'MOVE', 'REPORT']) end end describe '#get_csv' do specify do expect(FileParser::CSVParser.new(csv_file).send(:get_csv, csv_file)) .to eq([ ['PLACE 1,2,EAST', nil], ['MOVE', nil], ['MOVE', nil], ['LEFT', nil], ['MOVE', nil], ['REPORT', nil], [] ]) end end end
FactoryGirl.define do factory :shipping_matrix_rule, class: Spree::ShippingMatrixRule do association :matrix, factory: :shipping_matrix association :role min_line_item_total 25 amount 2.99 end end
require "application_system_test_case" class GoodsTest < ApplicationSystemTestCase setup do @good = goods(:one) end test "visiting the index" do visit goods_url assert_selector "h1", text: "Goods" end test "creating a Good" do visit goods_url click_on "New Good" fill_in "Article", with: @good.article check "Availability" if @good.availability fill_in "Content", with: @good.content fill_in "Name", with: @good.name fill_in "Razdel", with: @good.razdel_id fill_in "Rubles", with: @good.rubles click_on "Create Good" assert_text "Good was successfully created" click_on "Back" end test "updating a Good" do visit goods_url click_on "Edit", match: :first fill_in "Article", with: @good.article check "Availability" if @good.availability fill_in "Content", with: @good.content fill_in "Name", with: @good.name fill_in "Razdel", with: @good.razdel_id fill_in "Rubles", with: @good.rubles click_on "Update Good" assert_text "Good was successfully updated" click_on "Back" end test "destroying a Good" do visit goods_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Good was successfully destroyed" end end
require 'spec_helper' describe EssayStylesController do let(:issue) { FactoryBot.create(:issue) } let(:essay_style) { FactoryBot.create(:essay_style) } describe "#show" do it "succeeds" do get :show, issue_id: issue.friendly_id, id: essay_style.friendly_id expect(response).to be_success end end end
class CreateFlats < ActiveRecord::Migration[5.1] def change create_table :flats do |t| t.float :length t.float :width t.boolean :for_sale, :default => false t.boolean :for_rent, :default => false t.boolean :is_balcony t.boolean :is_parking t.boolean :is_garden t.boolean :is_furnished t.integer :no_of_bedrooms t.integer :no_of_hall t.integer :no_of_kitchen t.integer :no_of_bathrooms t.integer :age_of_building t.integer :total_floors t.integer :flat_at_floor t.integer :saleable_floor t.text :address t.string :city t.string :pincode t.string :state t.string :country t.text :description t.text :images t.references :land_lord t.timestamps end end end
module RedmineUserDefaultGroup # Patches Redmine's Users dynamically. Adds a +after_create+ filter. module UserPatch def self.included(base) # :nodoc: base.send(:include, InstanceMethods) # Same as typing in the class base.class_eval do unloadable # Send unloadable so it will not be unloaded in development after_create :add_default_group_to_user end end module InstanceMethods def add_default_group_to_user groups = Group.where('LOWER(lastname) = ?', Setting.plugin_redmine_user_default_group['group'].downcase) groups.first.users << self unless groups.empty? end end end end User.send(:include, RedmineUserDefaultGroup::UserPatch)
class Workout < ActiveRecord::Base attr_accessor :trained_on_date # Associations belongs_to :user has_many :workout_items, :dependent => :destroy has_many :exercises, :through => :workout_items # Scopes scope :starting_from, lambda { |date| {:conditions => ["trained_on <= ?", date] }} scope :on, lambda { |date| {:conditions => ["trained_on >= ? AND trained_on <= ?", date.beginning_of_day, date.end_of_day], :order => "trained_on ASC"} } #scope :today, :conditions => ["trained_on >= ? AND trained_on <= ?", Time.zone.now.beginning_of_day, Time.zone.now.end_of_day] scope :today, :conditions => ["trained_on = ?", Date.today] #this is my code. old code is above scope :past_week, :conditions => ["trained_on >= ?", 6.days.ago] scope :past_month, :conditions => ["trained_on >= ?", 30.days.ago] # Nested Attributes accepts_nested_attributes_for :workout_items, :allow_destroy => true # Instance Methods def trained_on_date=(hash) self.trained_on = Time.zone.parse("#{hash[:date]} #{hash[:time][:hour]}:#{hash[:time][:minute]} #{hash[:time][:meridian]}") end def total_calories workout_items.inject(0){|memo, workout_item| memo += workout_item.calories } end end
class CreateClaimNotes < ActiveRecord::Migration def change create_table :claim_notes do |t| t.string :title t.integer :claim_note_category_id t.text :body t.integer :claim_id t.timestamps null: false end end end
require 'boxzooka/xml/serialization_helper' require 'ox' module Boxzooka module Xml # Serializes a descendant of BaseElement to XML. class Serializer include Boxzooka::Xml::SerializationHelper # +obj+: the object to serialize. # +node_name+: optional override for the base node name. def initialize(object, node_name: nil) @object = object @node_name = node_name end # Serialized element. def xml @xml ||= build_xml end private attr_reader :object def build_xml doc = new_doc root_node = new_node(root_node_name) klass.field_names.each do |field_name| serialize_field_and_add_to_node(field_name, root_node) end doc << root_node # Output the XML. Ox.dump(doc) end def field_value(field_name) object.send(field_name) end def klass object.class end def new_doc Ox::Document.new(version: '1.0') end def new_node(node_name, internals = nil) el = Ox::Element.new(node_name) if internals el << internals end el end def root_node_name # Node name specified by argument. @node_name || # Node name specified by class. super end def serialize_field_and_add_to_node(field_name, node) node_name = field_node_name(field_name) field_klass = field_class(field_name) value = field_value(field_name) return if value.nil? case field_type(field_name) when FieldTypes::SCALAR then node << new_node(node_name, serialize_scalar_value(value, field_klass)) when FieldTypes::ENTITY then node << Ox.parse(Xml.serialize(value, node_name: node_name)) when FieldTypes::COLLECTION then serialize_collection_and_add_to_node(field_name, node) else raise NotImplementedError end nil end def serialize_scalar_value(value, type) case type when ScalarTypes::DATETIME value.strftime('%Y-%m-%d %H:%M:%S') else value.to_s end end def serialize_collection_and_add_to_node(field_name, node) node_name = field_node_name(field_name) serialize_to_flat = flat_collection?(field_name) entry_field_type = entry_field_type(field_name) entry_node_name = entry_node_name(field_name) entry_nodes = field_value(field_name).map do |entry| if entry_field_type == FieldTypes::SCALAR new_node( entry_node_name, serialize_scalar_value(entry, entry_type(field_name)) ) else Ox.parse(Xml.serialize(entry, node_name: entry_node_name)) end end if serialize_to_flat entry_nodes.each { |n| node << n } else collection_node = new_node(node_name) entry_nodes.each { |n| collection_node << n } node << collection_node end nil end end end end
class CreateRelationship < ActiveRecord::Migration[4.2] def change create_table :relationships do |t| t.integer :source_id, null: false t.integer :target_id, null: false t.belongs_to :user t.string :relationship_type, null: false, index: true t.float :original_weight, :float, default: 0 t.jsonb :original_details, default: '{}' t.string :original_relationship_type t.string :original_model t.integer :original_source_id t.string :original_source_field t.integer :confirmed_by t.datetime :confirmed_at t.float :weight, default: 0 t.string :source_field, default: nil t.string :target_field, default: nil t.string :model, default: nil t.jsonb :details, default: '{}' t.timestamps null: false end add_index :relationships, [:source_id, :target_id, :relationship_type], unique: true, name: 'relationship_index' end end
class Server < ActiveRecord::Base attr_accessible :name, :team_id belongs_to :team has_many :services, dependent: :destroy has_many :properties, dependent: :destroy has_many :checks, dependent: :destroy has_many :users, dependent: :destroy validates :name, presence: true, uniqueness: { scope: :team_id, message: "already taken" } validates :team, presence: { message: "must exist" } def self.ordered; order('team_id ASC, name ASC, id DESC') end # Standard permissions def self.can_new?(member,team_id) member.whiteteam? end def can_show?(member,team_id) member.whiteteam? || member.team_id == team_id end def can_edit?(member,team_id) member.whiteteam? end def can_create?(member,team_id) member.whiteteam? end def can_update?(member,team_id) member.whiteteam? end def can_destroy?(member,team_id) member.whiteteam? end end
require 'spec_helper' describe 'login cookie' do before :each do User.delete_all user end let(:user) { User.create(email: 'test@example.com', password: 'test') } it 'creates login cookie after user logging in' do visit '/users/sign_in' login assert_logged_in cookies['user_token'].should_not be_nil end it 'logs user out once user cookie has been deleted' do visit '/users/sign_in' login assert_logged_in delete_cookie('user_token') visit '/' assert_login_path end it 'allows user to log in with across multiple subdomains' do visit 'http://au.localtest.me:5000/users/sign_in' login assert_logged_in visit 'http://nz.localtest.me:5000/' assert_logged_in end it 'clears login token once user logs out' do visit '/users/sign_in' login assert_logged_in visit '/users/sign_out' cookies['user_token'].should be_nil end def assert_logged_in page.should have_content "Logged in" end def assert_login_path page.current_url.should include "/users/sign_in" end end
module Bowling class BowlingLeaguesController < ApplicationController skip_before_action :verify_authenticity_token before_action :authorize_user, :set_league def index @leagues = current_user.bowling_leagues.order(updated_at: :asc) end def export BowlingExporter.export(@league) end def new render :form end def edit render :form end def create @league = BowlingLeague.create(league_params.merge(user: current_user)) if @league.persisted? redirect_to @league else render :form end end def update if @league.update(league_params) redirect_to @league else render :form end end def destroy if @league.destroy redirect_to bowling_games_path else render :form end end def tms @stats = BowlingStatsCalculator.call(@league) end private def set_league if params[:id].present? @league = current_user.bowling_leagues.find(params[:id]) else @league = BowlingLeague.new end end def league_params params.require(:bowling_league).permit( :name, :team_name, :hdcp_base, :hdcp_factor, :absent_calculation, :games_per_series, :team_size, bowlers_attributes: [ :_destroy, :id, :name, :position, :total_games_offset, :total_pins_offset, ] ) end end end
class Student < ActiveRecord::Base #validates :student_name, presence: true validates :Age, presence: true validates :terms_of_service, acceptance: { accept: true } validates :email, presence: true, confirmation: true, uniqueness: true validates :email_confirmation, presence: true validates :pincode, length: { is: 6 , message: 'is of wrong length (should contain 6 numeric)' } before_create do self.student_name = student_name.capitalize unless student_name.blank? end before_validation :ensure_name_has_a_value protected def ensure_name_has_a_value if student_name.empty? self.student_name = email unless email.blank? end end after_validation :change_student_name protected def change_student_name if student_name.present? self.student_name = 'Vishal' end end end
require "./lib/cyrus-code-challenge/version" Gem::Specification.new do |spec| spec.name = 'cyrus-code-challenge' spec.version = CyrusCodeChallenge::VERSION spec.licenses = ['MIT'] spec.summary = "My solution for the cyrus-code-challenge, packaged into a CLI gem." spec.author = ["Brennen Awana"] spec.email = 'brennenawana108ny@gmail.com' spec.files = (['env.rb'] + Dir['lib/*.rb'] + Dir['lib/cyrus-code-challenge/*.rb'] + Dir['data/*.txt'] + Dir['bin/*']).to_a spec.require_paths = ["lib", "data/input_files", "lib/cyrus-code-challenge"] spec.executables = ["cyrus-code-challenge"] spec.homepage = 'https://github.com/the-widget/code-challenge' end
class CreateItemReagents < ActiveRecord::Migration def change create_table :item_reagents do |t| t.date :shelf_life t.string :conservation t.string :current_volume t.string :current_weight end end end
class CreateEntryPhotos < ActiveRecord::Migration def change create_table :entry_photos do |t| t.belongs_to :entry t.belongs_to :photo t.timestamps end add_index :entry_photos, :entry_id add_index :entry_photos, :photo_id end end
module RubyMotionQuery class RMQ # @return [RMQ] def attr(new_settings) selected.each do |view| new_settings.each do |k,v| view.send "#{k}=", v end end self end # Get or set the most common data for a particuliar view(s) in a # performant way (more performant than attr) # For example, text for UILabel, image for UIImageView # # @return [RMQ] def data(new_data = :rmq_not_provided) if new_data != :rmq_not_provided selected.each do |view| case view when NSTextField then view.setStringValue new_data when NSButton then view.title = new_data # TODO, finish end end self else out = selected.map do |view| case view when NSTextField then view.stringValue when NSButton then view.title # TODO, finish end end out = out.first if out.length == 1 out end end # Allow users to set data with equals # # @return [RMQ] # # @example # rmq(my_view).data = 'some data' def data=(new_data) self.data(new_data) end # @return [RMQ] def send(method, args = nil) selected.each do |view| if view.respond_to?(method) if args view.__send__ method, args else view.__send__ method end end end self end # Sets the last selected view as the first responder # # @return [RMQ] # # @example # rmq(my_view).next(UITextField).focus def focus unless RMQ.is_blank?(selected) selected.last.becomeFirstResponder end self end alias :become_first_responder :focus # @return [RMQ] def hide selected.each { |view| view.hidden = true } self end # @return [RMQ] def show selected.each { |view| view.hidden = false } self end # @return [RMQ] def toggle selected.each { |view| view.hidden = !view.hidden? } self end # @return [RMQ] def toggle_enabled selected.each { |view| view.enabled = !view.enabled? } self end def enable selected.each { |view| view.enabled = true } self end def disable selected.each { |view| view.enabled = false } self end def enable_interaction selected.each { |view| view.userInteractionEnabled = true } self end def disable_interaction selected.each { |view| view.userInteractionEnabled = false } self end # For UIActivityIndicatorViews def start_animating selected.each do |view| view.startAnimating if view.respond_to?(:startAnimating) end self end # For UIActivityIndicatorViews def stop_animating selected.each do |view| view.stopAnimating if view.respond_to?(:startAnimating) end self end end end
class DataCorrection < LoanModification include FormatterConcern belongs_to :old_lending_limit, class_name: 'LendingLimit' belongs_to :lending_limit format :postcode, with: PostcodeFormatter format :old_postcode, with: PostcodeFormatter end
module RealEstatesDescriptors FLATS_DESCRIPTORS = [:storey, :has_balcony, :furnished, :has_roof, :has_garden, :has_elevator, :cellar, :rooms, :baths, :direction, # both direction and direction: [] NEED to be listed :flat_type, :furnished_description, :storey_total, :legal, direction: []].freeze VILLAS_DESCRIPTORS = [:number_of_storeies, :furnished, :has_garden, :has_elevator, :cellar, :rooms, :baths].freeze LANDS_DESCRIPTORS = [].freeze ROOMS_DESCRIPTORS = [:storey, :cellar, :has_balcony, :furnished, :has_elevator, :baths, :beds].freeze SHOPS_DESCRIPTORS = [:storey, :cellar, :furnished, :has_elevator, :baths].freeze BUILDINGS_DESCRIPTORS = [:number_of_storeies, :number_of_flats, :has_elevator].freeze FARMS_DESCRIPTORS = [:rooms, :baths, :furnished].freeze def m_helper @helper end end
module Ricer::Plug class Password def initialize(string) @string = string end def empty? @string.nil? || @string.empty? end def to_s @string.nil? ? '' : @string.to_s end def length empty? ? 0 : @string.length end def matches?(password) empty? ? false : BCrypt::Password.new(@string).is_password?(password) end end end
class Product < ActiveRecord::Base validates :name, :quantity_in_stock, :price, presence: true validates :quantity_in_stock, numericality: {greater_than_or_equal_to: 1} validates :price, numericality: {greater_than_or_equal_to: 0.01} validates :name, uniqueness: true has_many :cart_items end
def hello(name) "Hello, " + name end def starts_with_consonant?(s) first_letter = s[0, 1].upcase consonants = [*('B'..'H'),*('J'..'N'),*('P'..'T'),*('V'..'Z')] consonants.each do |x| if x == first_letter return true end end return false end =begin Original starts_with_consonant, I changed it to a large defined array, because it couldn't handle one of the rules for hw0 def starts_with_consonant?(s) if s =~ /^[^aeiou]/i return true else return false end end =end def binary_multiple_of_4?(s) if s =~ /^[01]*1[01]*00$/ return true else return false end end
module GitAnalysis # prints information about the repository class Printer attr_reader :repo attr_reader :open_pr_count attr_reader :closed_pr_count def initialize(repo_object, open_pr_count, closed_pr_count) @repo = repo_object @open_pr_count = open_pr_count @closed_pr_count = closed_pr_count end # print repo ID, name, owner, language def basic_info "ID: #{@repo.id}\nName: #{@repo.name}\nOwner: #{@repo.owner}\nLanguage: #{@repo.language}\n" end # print the number of open and closed pull requests def num_prs "Open PRs: #{open_pr_count}\nClosed PRs: #{closed_pr_count}\n" end # for each PR, print the size def pr_size(pr_object) "PR #{pr_object.number}\n Files: #{pr_object.file_count}\n Additions: #{pr_object.additions}\n Deletions: #{pr_object.deletions}\n Changes: #{pr_object.changes}\n" end end end
class Board attr_reader :grid class IllegalMoveError < StandardError; end def initialize(empty_board = false) @grid = Array.new(8) { Array.new(8) } set_board(@grid) unless empty_board @captured_pieces = [] end def in_check?(color) king = king_pos(color) check = false @grid.flatten.compact.each do |piece| if piece && piece.color != color && piece.moves.include?(king) puts "CHECK!" check = true end end check end def king_pos(color) @grid.flatten.each do |piece| if piece && piece.is_a?(King) && piece.color == color return piece.pos end end end def display puts "CHESS".center(28) @grid.each_with_index do |row, i| row_str = "#{8 - i} " row.each_with_index do |piece, j| new_string = piece ? piece.to_s : " \e[0m" row_str += background([i, j], new_string.center(3)) end puts row_str end footer = ' ' ('A'..'H').each { |letter| footer += "\e[36m#{letter.rjust(3)}\e[0m" } puts footer print_captured_pieces end def set_board(matrix) [:black, :white].each do |color| create_pawn_row(color, matrix) create_back_row(color, matrix) end end def create_pawn_row(color, matrix) row = color == :black ? 1 : 6 pawns = [] (0..7).each do |i| pawns << Pawn.new([row, i], color, self) end matrix[row] = pawns end def create_back_row(color, matrix) row = color == :black ? 0 : 7 new_pieces = [ Rook.new([row, 0], color, self), Knight.new([row, 1], color, self), Bishop.new([row, 2], color, self), Queen.new([row, 3], color, self), King.new([row, 4], color, self), Bishop.new([row, 5], color, self), Knight.new([row, 6], color, self), Rook.new([row, 7], color, self), ] matrix[row] = new_pieces end def move(pos1, pos2) piece = self[pos1] target = self[pos2] begin raise IllegalMoveError.new("Can't move empty place") if !piece moves = piece.valid_moves raise IllegalMoveError.new("Illegal move")if !moves.include?(pos2) if piece && target capture_piece(piece, target) else self[pos1], self[pos2] = self[pos2], self[pos1] end piece.update_pos return true rescue IllegalMoveError => e puts "IllegalMoveError: #{e}" return false end end def capture_piece(piece, target) self[target.pos] = piece @captured_pieces << target self[piece.pos] = nil end def print_captured_pieces captured_str = "Captured: " @captured_pieces.each {|piece| captured_str += piece.to_s.rjust(3)} puts captured_str end def checkmate?(color) @grid.flatten.compact.each do |piece| next if piece.color != color return false unless piece.valid_moves.empty? end true end # moving for tests def move!(pos1, pos2) begin piece = self[pos1] raise IllegalMoveError.new("Can't move empty place") if !piece moves = piece.moves target = self[pos2] raise IllegalMoveError.new("Illegal move")if !moves.include?(pos2) self[pos1], self[pos2] = self[pos2], self[pos1] piece.update_pos rescue IllegalMoveError => e puts "IllegalMoveError: #{e}" end end def find(piece) @grid.each_with_index do |row, i| row.each_with_index { |col, j| return [i, j] if col == piece } end end def dup dup_board = Board.new(true) @grid.flatten.compact.each do |piece| new_position = piece.pos new_color = piece.color new_piece = piece.class.new(new_position, new_color, dup_board ) dup_board[piece.pos] = new_piece end dup_board end def [](pos) row, col = pos[0],pos[1] @grid[row][col] end def []=(pos, piece) row, col = pos[0],pos[1] @grid[row][col] = piece end def background(pos, string) background = "" if pos[0].even? background = pos[1].even? ? "\e[1;100m" : "\e[47m" else background = pos[1].odd? ? "\e[1;100m" : "\e[47m" end background + string end end
require 'rails_helper' RSpec.describe 'Profile Item Types API' do let!(:profile_item_type1) { create(:profile_item_type, code: 'ENTH', type_code: 'VALU' )} let!(:profile_item_type2) { create(:profile_item_type, code: 'HGHT', type_code: 'MIMA' )} let!(:profile_item_type3) { create(:profile_item_type, code: 'BRAS', type_code: 'CONV' )} let!(:profile_value_item_type_value) { create(:profile_value_item_type_value, profile_item_type_code: 'ENTH', profile_item_type_id: profile_item_type1.id, name: 'Chinese' ) } let!(:profile_range_item_type_value) { create(:profile_range_item_type_value, profile_item_type_code: 'HGHT', profile_item_type_id: profile_item_type2.id, min: 150, max:250, step: 1 ) } let!(:conversion) { create(:conversion, profile_item_type_code: 'BRAS', profile_item_type_id: profile_item_type3.id, sequence: 1, uk_value: '11', eu_value: '11', au_value: '11', fr_value: '11' ) } describe 'GET /profile_value_item_type_values' do before { get '/profile_item_types'} it 'return status code 200' do expect(response).to have_http_status(200) end it 'return profile item types' do pp json expect(json).not_to be_empty expect(json.size).to eq(3) end end describe 'GET /profile_item_types/ethnicities' do before { get '/profile_item_types/ethnicities'} it 'return status code 200' do expect(response).to have_http_status(200) end it 'return profile item types' do expect(json).not_to be_empty expect(json.size).to eq(1) end end end
require "spec_helper" module Scenic describe Scenic::Statements do before do allow(Scenic).to receive(:database) .and_return(class_double("Scenic::Adapters::Postgres").as_null_object) end describe "create_view" do it "creates a view from a file" do version = 15 definition_stub = instance_double("Definition", to_sql: "foo") allow(Definition).to receive(:new) .with(:views, version) .and_return(definition_stub) connection.create_view :views, version: version expect(Scenic.database).to have_received(:create_view) .with(:views, definition_stub.to_sql) end it "creates a view from a text definition" do sql_definition = "a defintion" connection.create_view(:views, sql_definition: sql_definition) expect(Scenic.database).to have_received(:create_view) .with(:views, sql_definition) end it "raises an error if neither version nor sql_defintion are provided" do expect do connection.create_view :foo, version: nil, sql_definition: nil end.to raise_error ArgumentError end end describe "drop_view" do it "removes a view from the database" do connection.drop_view :name expect(Scenic.database).to have_received(:drop_view).with(:name) end end describe "update_view" do it "drops the existing version and creates the new" do definition = instance_double("Definition", to_sql: "definition") allow(Definition).to receive(:new) .with(:name, 3) .and_return(definition) connection.update_view(:name, version: 3) expect(Scenic.database).to have_received(:drop_view).with(:name) expect(Scenic.database).to have_received(:create_view) .with(:name, definition.to_sql) end it "raises an error if not supplied a version" do expect { connection.update_view :views } .to raise_error(ArgumentError, /version is required/) end end def connection Class.new { extend Statements } end end end
class SongsController < ApplicationController def index @genre = Genre.find(params[:genre_id]) @songs = @genre.songs end def show @song = Song.find(params[:id]) @genres = @song.genres end def new @genres = Genre.all end def create # manual way: # new_song = Song.new # new_song.name = params[:song][:name] # params[:song][:genre_ids].each do |genre_id| # if !genre_id.blank? # genre = Genre.find(genre_id) # new_song.genres << genre # end # end # new_song.save # ruby way: new_song = Song.new(song_params) new_song.save redirect_to new_song end def edit @song = Song.find(params[:id]) @genres = Genre.all end def update song = Song.find(params[:id]) song.update(song_params) redirect_to song end def destroy song = Song.find(params[:id]) song.destroy redirect_to '/' end private def song_params params.require(:song).permit(:name, :genre_ids => []) end end
require "spec_helper" describe AreaBasePricesController do describe "routing" do it "routes to #index" do get("/area_base_prices").should route_to("area_base_prices#index") end it "routes to #new" do get("/area_base_prices/new").should route_to("area_base_prices#new") end it "routes to #show" do get("/area_base_prices/1").should route_to("area_base_prices#show", :id => "1") end it "routes to #edit" do get("/area_base_prices/1/edit").should route_to("area_base_prices#edit", :id => "1") end it "routes to #create" do post("/area_base_prices").should route_to("area_base_prices#create") end it "routes to #update" do put("/area_base_prices/1").should route_to("area_base_prices#update", :id => "1") end it "routes to #destroy" do delete("/area_base_prices/1").should route_to("area_base_prices#destroy", :id => "1") end end end
class QuestionsController < ApplicationController before_filter :set_question, only: [:show, :results] before_filter :check_secret_is_unique, only: [:create] def new @question = Question.new @option = Option.new end def create @question = Question.new(question_params) @question.secret = SecureRandom.urlsafe_base64(nil, false)[0, 5] unless @question.secret? if @question.q_type != 2 @question.q_type = 1 end @question.save! params[:options].each_with_index do |option, index| if option[:title] != "" new_option = Option.new new_option.title = option[:title] new_option.question_id = @question.id if params.include? :answer if params[:answer][index.to_s] == "1" && @question.q_type == 2 new_option.correct = 1 elsif @question.q_type == 2 new_option.correct = 0 end end new_option.save! end end redirect_to "/#{@question.secret}" end def show vote_id = cookies["vote_#{@question.secret}"] @vote = Vote.where({secret: vote_id}).first_or_initialize end def results @options = @question.options @qr = RQRCode::QRCode.new("lefred.be:3000/"+@question.secret, :size => 3, :level => :h).to_img.resize(300, 300).to_data_url end def check_secret_availability render json: { available: !Question.where({secret: params[:secret]}).exists? } end private def set_question @question = Question.where({secret: params[:secret]}).first end def question_params params.require(:question).permit(:title, :secret, :q_type) end def check_secret_is_unique if defined? params[:question][:secret] if Question.where({secret: params[:question][:secret]}).exists? @question = Question.new(question_params) redirect_to :back, notice: 'Sorry that URL is taken' end end end end
class DonationsController < ApplicationController before_action :authenticate_user! before_filter :require_permission skip_before_filter :authenticate_user!, :only => [:payment_notify] skip_before_filter :require_permission, :only => [:payment_notify] skip_before_filter :verify_authenticity_token, :only => [:payment_notify] def index @donations = Donation.includes(:user).all.order("date DESC, id DESC") end def new @donation = Donation.new end def create if params[:user_email].present? user = User.find_by_email(params[:user_email].downcase) params[:donation][:user_id] = user.id if user.present? end @donation = Donation.create(entry_params) if @donation.save flash[:notice] = "Donation added successfully!" if user.present? && params[:donation][:send_thanks] == 1 UserMailer.thanks_for_donating(user).deliver_later end redirect_to donations_path else render 'new' end end def edit @donation = Donation.find(params[:id]) end def update @donation = Donation.find(params[:id]) if params[:user_email].present? user = User.find_by_email(params[:user_email]) params[:donation][:user_id] = user.id if user.present? end if @donation.update(entry_params) flash[:notice] = "Donation successfully updated!" redirect_to donations_path else render 'edit' end end def show @donation = Donation.find(params[:id]) end def destroy @donation = Donation.find(params[:id]) @donation.destroy flash[:notice] = "Donation deleted successfully." redirect_to donations_path end def payment_notify # check for GUMROAD if params[:email].present? && params[:seller_id].gsub("==","") == ENV['GUMROAD_SELLER_ID'] && params[:product_id].gsub("==","") == ENV['GUMROAD_PRODUCT_ID'] user = User.find_by_email(params[:email]) if user.present? && user.donations.count > 0 && Donation.where(user_id: user.id).last.created_at.to_date === Time.now.to_date #duplicate, don't send elsif user.present? paid = params[:price].to_f / 100 donation = Donation.create(user_id: user.id, comments: "Gumroad monthly from #{user.email}", date: "#{Time.now.strftime("%Y-%m-%d")}", amount: paid ) UserMailer.thanks_for_donating(user).deliver_later if user.donations.count == 1 end elsif params[:item_name].present? && params[:item_name].include?("Dabble Me Pro for") && params[:payment_status].present? && params[:payment_status] == "Completed" && ENV['AUTO_EMAIL_PAYPAL'] == "yes" # check for Paypal email = params[:item_name].gsub("Dabble Me Pro for ","") if params[:item_name].present? user = User.find_by_email(email) if user.blank? # try finding user based on payer_email instead of item_name email = params[:payer_email] if params[:payer_email].present? user = User.find_by_email(email) end if user.present? && user.donations.count > 0 && Donation.where(user_id: user.id).last.created_at.to_date === Time.now.to_date # duplicate, don't send elsif user.present? paid = params[:mc_gross] donation = Donation.create(user_id: user.id, comments: "Paypal monthly from #{params[:payer_email]}", date: "#{Time.now.strftime("%Y-%m-%d")}", amount: paid ) UserMailer.thanks_for_donating(user).deliver_later if user.donations.count == 1 end end head :ok, content_type: "text/html" end private def entry_params params.require(:donation).permit(:amount, :date, :user_id, :comments) end def require_permission unless current_user.is_admin? flash[:alert] = "Not authorized" redirect_to past_entries_path end end end
class RecipesController < ApplicationController skip_before_action :authenticate_user!, only: [ :index, :api ] before_action :find_recipe, only: [ :index, :api ] def index recipe_params = [] Recipe.all.each do |recipe| recipe_params << [ recipe.carbs, recipe.fat, recipe.protein ] end index = Ngt::Index.new(3) index.batch_insert(recipe_params) query = recipe_params[@recipe.id - 1] @result = index.search(query, size: 3) @recipes = [ @recipe, Recipe.find(@result[1][:id]), Recipe.find(@result[2][:id]) ] end def api @recipe = Recipe.find(params[:query]) render json: @recipe end private def find_recipe @recipe = Recipe.find(params[:query]) end end
class AddUniqToItems < ActiveRecord::Migration[5.1] def change add_index :items, :cid, :unique => true end end
require 'spec_helper' describe Guild do before(:each) do end it "should create a new instance given valid attributes" do Factory.create(:Guild) end it "should know its characters" do @guild = Factory.create(:Guild) @characters = [Factory.create(:Character),Factory.create(:Character)] @guild.characters << @characters @guild.characters.count.should == 2 end it "should can get some RemoteQueries" do @guild = Factory.create(:Guild) @remotequeries = [Factory.create(:RemoteQuery),Factory.create(:RemoteQuery)] @guild.remoteQueries << @remotequeries @guild.remoteQueries.count.should == 2 end it "shouldn't accept a description with lesser then 100 Characters" do @guild = Factory.build(:Guild, :description => "Too short man!!") @guild.valid?.should be_false @guild.should have_at_least(1).error_on(:description) end it "should not be valid without a name" do @guild = Factory.build(:Guild, :name => "") @guild.valid?.should be_false @guild.should have_at_least(1).error_on(:name) end it "should not be valid without a token" do @guild = Factory.build(:Guild, :token => "") @guild.valid?.should be_false @guild.should have_at_least(1).error_on(:token) end it "should know its raidleaders" do @guild = Factory(:Guild) Factory(:Role,:name => 'raidleader') raidleader = Factory(:User) @guild.assignments << Assignment.create(:user_id => raidleader.id, :guild_id => @guild.id, :role_id => Role.find_by_name('raidleader')) @guild.raidleaders.first.should == raidleader end it "should know its leaders" do @guild = Factory(:Guild) Factory(:Role,:name => 'leader') leader = Factory(:User) @guild.assignments << Assignment.create(:user_id => leader.id, :guild_id => @guild.id, :role_id => Role.find_by_name('leader')) @guild.leaders.first.should == leader end it "should know its officers" do @guild = Factory(:Guild) Factory(:Role,:name => 'officer') officer = Factory(:User) @guild.assignments << Assignment.create(:user_id => officer.id, :guild_id => @guild.id, :role_id => Role.find_by_name('officer')) @guild.officers.first.should == officer end it "should know its members" do @guild = Factory(:Guild) Factory(:Role,:name => 'member') member = Factory(:User) @guild.assignments << Assignment.create(:user_id => member.id, :guild_id => @guild.id, :role_id => Role.find_by_name('member')) @guild.members.first.should == member end end
class RenameColumn < ActiveRecord::Migration def up rename_column :links, :author_id, :user_id end def down end end
class Search < ApplicationRecord RESOURCES = %w[Question Answer User Comment].freeze def self.find(query, search_object = nil) search_object&.capitalize! object = search_object.in?(RESOURCES) ? search_object.constantize : ThinkingSphinx object.search(query) end end
# Add estimation sessions reference class AddEstimationSessionRefToProjects < ActiveRecord::Migration[5.0] def change add_reference :projects, :estimation_session, foreign_key: true end end
class MediaController < ApplicationController def show type = params[:type] id = params[:id].to_i if type == 'instagram' @media = fetch_instagram_media(id) elsif type == 's3' @media = fetch_s3_media(id) end render json: @media end private def fetch_instagram_media(id) post = Instagram.find(id) { url: (post.media_type == 'image') ? post.image_url : post.video_url, date: post.posted_at.strftime("%Y.%m.%d") } end def fetch_s3_media(id) post = S3.find(id) { url: "#{ENV['S3_HOST']}/#{ENV['S3_BUCKET']}/#{post.key}}", date: post.shooted_at.strftime("%Y.%m.%d") } end end
module JanusGateway class Resource::Plugin < Resource # @return [JanusGateway::Resource::Session] attr_reader :session # @return [String] attr_reader :name # @param [JanusGateway::Client] client # @param [JanusGateway::Resource::Session] session # @param [String] plugin_name def initialize(client, session, plugin_name) @session = session @name = plugin_name super(client) end # @return [Concurrent::Promise] def create promise = Concurrent::Promise.new client.send_transaction( janus: 'attach', plugin: name, session_id: @session.id ).then do |*args| _on_created(*args) promise.set(self).execute end.rescue do |error| promise.fail(error).execute end promise end def destroy promise = Concurrent::Promise.new _on_destroyed promise.set(self).execute promise end private def _on_created(data) @id = data['data']['id'] session.on :destroy do |_data| destroy end emit :create end def _on_destroyed emit :destroy end end end
describe Inventory do let(:inventory) { Inventory.new } let(:cart) { inventory.new_cart } describe "with no discounts" do it "can tell the total price of all products" do inventory.register 'The Best of Coltrane CD', '1.99' cart.add 'The Best of Coltrane CD' cart.add 'The Best of Coltrane CD' cart.total.should eq '3.98'.to_d end it "has some constraints on prices and counts" do inventory.register 'Existing', '1.00' inventory.register 'Top price', '999.99' inventory.register 'A' * 40, '1.99' cart.add 'Top price', 99 expect { inventory.register 'Existing' }.to raise_error expect { inventory.register 'Negative', '-10.00' }.to raise_error expect { inventory.register 'Zero', '0.00' }.to raise_error expect { inventory.register 'L' * 41, '1.00' }.to raise_error expect { inventory.register 'Overpriced', '1000.0' }.to raise_error expect { cart.add 'Unexisting' }.to raise_error expect { cart.add 'Existing', 100 }.to raise_error expect { cart.add 'Existing', -1 }.to raise_error end it "can print an invoice" do inventory.register 'Green Tea', '0.79' inventory.register 'Earl Grey', '0.99' inventory.register 'Black Coffee', '1.99' cart.add 'Green Tea' cart.add 'Earl Grey', 3 cart.add 'Black Coffee', 2 cart.invoice.should eq <<INVOICE +------------------------------------------------+----------+ | Name qty | price | +------------------------------------------------+----------+ | Green Tea 1 | 0.79 | | Earl Grey 3 | 2.97 | | Black Coffee 2 | 3.98 | +------------------------------------------------+----------+ | TOTAL | 7.74 | +------------------------------------------------+----------+ INVOICE end end describe "with a 'buy X, get one free' promotion" do it "grants every nth item for free" do inventory.register 'Gum', '1.00', get_one_free: 4 cart.add 'Gum', 4 cart.total.should eq '3.00'.to_d end it "grants 2 items free, when 8 purchased and every 3rd is free" do inventory.register 'Gum', '1.00', get_one_free: 3 cart.add 'Gum', 8 cart.total.should eq '6.00'.to_d end it "shows the discount in the invoice" do inventory.register 'Green Tea', '1.00', get_one_free: 3 inventory.register 'Red Tea', '2.00', get_one_free: 5 cart.add 'Green Tea', 3 cart.add 'Red Tea', 8 cart.invoice.should eq <<INVOICE +------------------------------------------------+----------+ | Name qty | price | +------------------------------------------------+----------+ | Green Tea 3 | 3.00 | | (buy 2, get 1 free) | -1.00 | | Red Tea 8 | 16.00 | | (buy 4, get 1 free) | -2.00 | +------------------------------------------------+----------+ | TOTAL | 16.00 | +------------------------------------------------+----------+ INVOICE end end describe "with a '% off for every n' promotion" do it "gives % off for every group of n" do inventory.register 'Sandwich', '1.00', package: {4 => 20} cart.add 'Sandwich', 4 cart.total.should eq '3.20'.to_d cart.add 'Sandwich', 4 cart.total.should eq '6.40'.to_d end it "does not discount for extra items, that don't fit in a group" do inventory.register 'Sandwich', '0.50', package: {4 => 10} cart.add 'Sandwich', 4 cart.total.should eq '1.80'.to_d cart.add 'Sandwich', 2 cart.total.should eq '2.80'.to_d end it "shows the discount in the invoice" do inventory.register 'Green Tea', '1.00', package: {4 => 10} inventory.register 'Red Tea', '2.00', package: {5 => 20} cart.add 'Green Tea', 4 cart.add 'Red Tea', 8 cart.invoice.should eq <<INVOICE +------------------------------------------------+----------+ | Name qty | price | +------------------------------------------------+----------+ | Green Tea 4 | 4.00 | | (get 10% off for every 4) | -0.40 | | Red Tea 8 | 16.00 | | (get 20% off for every 5) | -2.00 | +------------------------------------------------+----------+ | TOTAL | 17.60 | +------------------------------------------------+----------+ INVOICE end end describe "with a '% off of every item after the nth' promotion" do it "gives a discount for every item after the nth" do inventory.register 'Coke', '2.00', threshold: {5 => 10} cart.add 'Coke', 8 cart.total.should eq '15.40'.to_d end it "does not give a discount if there are no more than n items in the cart" do inventory.register 'Coke', '1.00', threshold: {10 => 20} cart.add 'Coke', 8 cart.total.should eq '8.00'.to_d cart.add 'Coke', 2 cart.total.should eq '10.00'.to_d cart.add 'Coke', 5 cart.total.should eq '14.00'.to_d end it "shows the discount in the ivnoice" do inventory.register 'Green Tea', '1.00', threshold: {10 => 10} inventory.register 'Red Tea', '2.00', threshold: {15 => 20} cart.add 'Green Tea', 12 cart.add 'Red Tea', 20 cart.invoice.should eq <<INVOICE +------------------------------------------------+----------+ | Name qty | price | +------------------------------------------------+----------+ | Green Tea 12 | 12.00 | | (10% off of every after the 10th) | -0.20 | | Red Tea 20 | 40.00 | | (20% off of every after the 15th) | -2.00 | +------------------------------------------------+----------+ | TOTAL | 49.80 | +------------------------------------------------+----------+ INVOICE end end describe "with a '% off' coupon" do it "gives % off of the total" do inventory.register 'Tea', '1.00' inventory.register_coupon 'TEATIME', percent: 20 cart.add 'Tea', 10 cart.use 'TEATIME' cart.total.should eq '8.00'.to_d end it "applies the coupon discount after product promotions" do inventory.register 'Tea', '1.00', get_one_free: 6 inventory.register_coupon 'TEATIME', percent: 10 cart.add 'Tea', 12 cart.use 'TEATIME' cart.total.should eq '9.00'.to_d end it "shows the discount in the invoice" do inventory.register 'Green Tea', '1.00' inventory.register_coupon 'TEA-TIME', percent: 20 cart.add 'Green Tea', 10 cart.use 'TEA-TIME' cart.invoice.should eq <<INVOICE +------------------------------------------------+----------+ | Name qty | price | +------------------------------------------------+----------+ | Green Tea 10 | 10.00 | | Coupon TEA-TIME - 20% off | -2.00 | +------------------------------------------------+----------+ | TOTAL | 8.00 | +------------------------------------------------+----------+ INVOICE end end describe "with an 'amount off' coupon" do it "subtracts the amount form the total" do inventory.register 'Tea', '1.00' inventory.register_coupon 'TEATIME', amount: '10.00' cart.use 'TEATIME' cart.add 'Tea', 12 cart.total.should eq '2.00'.to_d end it "does not result in a negative total" do inventory.register 'Tea', '1.00' inventory.register_coupon 'TEATIME', amount: '10.00' cart.use 'TEATIME' cart.add 'Tea', 8 cart.total.should eq '0.00'.to_d end it "shows the discount in the invoice" do inventory.register 'Green Tea', '1.00' inventory.register_coupon 'TEA-TIME', amount: '10.00' cart.add 'Green Tea', 5 cart.use 'TEA-TIME' cart.invoice.should eq <<INVOICE +------------------------------------------------+----------+ | Name qty | price | +------------------------------------------------+----------+ | Green Tea 5 | 5.00 | | Coupon TEA-TIME - 10.00 off | -5.00 | +------------------------------------------------+----------+ | TOTAL | 0.00 | +------------------------------------------------+----------+ INVOICE end end describe "with multiple discounts" do it "can print an invoice" do inventory.register 'Green Tea', '2.79', get_one_free: 2 inventory.register 'Black Coffee', '2.99', package: {2 => 20} inventory.register 'Milk', '1.79', threshold: {3 => 30} inventory.register 'Cereal', '2.49' inventory.register_coupon 'BREAKFAST', percent: 10 cart.add 'Green Tea', 8 cart.add 'Black Coffee', 5 cart.add 'Milk', 5 cart.add 'Cereal', 3 cart.use 'BREAKFAST' cart.invoice.should eq <<INVOICE +------------------------------------------------+----------+ | Name qty | price | +------------------------------------------------+----------+ | Green Tea 8 | 22.32 | | (buy 1, get 1 free) | -11.16 | | Black Coffee 5 | 14.95 | | (get 20% off for every 2) | -2.39 | | Milk 5 | 8.95 | | (30% off of every after the 3rd) | -1.07 | | Cereal 3 | 7.47 | | Coupon BREAKFAST - 10% off | -3.91 | +------------------------------------------------+----------+ | TOTAL | 35.16 | +------------------------------------------------+----------+ INVOICE end end end
module ActiveEs module Schema module Definition extend ActiveSupport::Concern FieldDetaTypes = %w( text keyword long integer short byte double float half_float scaled_float date boolean binary integer_range float_range long_range double_range date_range ) def property(field, **options) if options.values.all? { |key| FieldDetaTypes.exclude?(key) } raise ArgumentError('invalid field deta types') end unless defined? properties class_attribute :properties, default: {} end properties[field] = options attr_accessor field end def create_schema client.indices.create index: index, body: mappings end def delete_schema client.indices.delete index: index end def reset_schema delete_schema create_schema end end end end
class AddTeamToSources < ActiveRecord::Migration def change add_column :sources, :team_id, :integer add_index :sources, :team_id Source.find_each do |s| u = s.user t = u.teams.first unless u.nil? s.update_columns(team_id: t.id) unless t.nil? end end end
require 'test_helper' class LowCreditUsersTest < ActiveSupport::TestCase test "low credit users" do rows = exec_low_credit_users assert_equal 2, rows.size low_credit_users = [users(:ljf), users(:jess)] user_ids = Set[rows.map {|u| u["user_id"]}] assert_equal Set[low_credit_users.map(&:id)], user_ids balances = Set[rows.map {|u| u["credit_balance"]}] assert_equal Set[low_credit_users.map(&:credits)], balances end test "doesnt charge for skip" do kyle = users(:kyle) menu = menus(:week2) pickup_day = menu.pickup_days.first # synthesize enough orders that kyle will be in the "low-credit" list items = menu.menu_items new_kyle_orders = kyle.credits.times.map do kyle.orders.create!(menu: menu).tap do |order| order.order_items.create!(item: items.sample.item, pickup_day: pickup_day) end end assert_equal 0, kyle.credits, 'now kyle has no credits' assert_equal 3, exec_low_credit_users.size, 'kyle included in low credit users' end test "dont show users who dont get emails" do User.all.update_all(subscriber: false) assert_equal 0, exec_low_credit_users.size end private def exec_low_credit_users SqlQuery.new(:low_credit_users, balance: 4).execute end end
class AddLegacyTradeCodesToTaxonConcepts < ActiveRecord::Migration def change add_column :taxon_concepts, :legacy_trade_code, :string end end
json.array!(@posts) do |post| json.color post.color.color json.url post_item_path(post.slug) json.picture image_url(post.picture.url(:preview)) json.title post.title json.announce post.announce.truncate(300).html_safe if post.announce json.categories post.categories.map{|c| [c.name, c.slug] } end
class TripsController < ApplicationController # To access Devise view in this controller before_action :configure_permitted_parameters, :if => :devise_controller? def resource_name :user end def resource @resource ||= User.new end def devise_mapping @devise_mapping ||= Devise.mappings[:user] end helper_method :resource, :resource_name, :devise_mapping # End devise def show begin @trip = Trip.find(params[:id]) rescue flash[:error] = "This trip does not exist." redirect_to(root_path) return end if current_user if UserTrip.where(user_id: current_user.id, trip_id: @trip.id).blank? flash[:notice] = "Ooops! Your account does not have permission to view this trip or itinerary. Please contact the owner of the trip give you access." render "no_permission" end else session[:previous_url] = request.fullpath flash[:notice] = "Ooops! You do not have permission to view this page. Please sign up or log in." render "devise/registrations/new" end end def generate_itinerary(trip_id) #"please generate an itinerary for me according to this trip_id" begin @trip = Trip.find(trip_id) @itinerary = @trip.generate_itinerary(@trip.city) redirect_to show_itinerary_path(:trip_id => trip_id) rescue flash[:error] = "This trip does not exist." redirect_to(root_path) end end def show_itinerary begin @trip = Trip.find(params[:trip_id]) @invitation_code = params[:invitation_code] if current_user is_owner = current_user.id == @trip.user_id is_participant = !UserTrip.where(user_id: current_user.id, trip_id: @trip.id).blank? has_correct_invitation = @invitation_code == @trip.uuid if is_owner || is_participant || has_correct_invitation # Has permission if !is_owner && !is_participant && has_correct_invitation UserTrip.create(user_id: current_user.id, trip_id: @trip.id) end has_itinerary = false trip_attractions = @trip.trip_attractions trip_attractions.each do |trip_attraction| if trip_attraction.start_time != nil has_itinerary = true break end end if has_itinerary if !is_owner && !is_participant trip_attractions.each do |trip_attraction| if !trip_attraction.attraction_id.nil? && !trip_attraction.lunch current_user.votes.create(trip_attraction: trip_attraction, attraction_id: trip_attraction.attraction_id, vote: 0) end end end @itinerary = TripAttraction.where(:trip_id => @trip.id).where.not(:start_time => nil).order(:start_time) render "show_itinerary" else generate_itinerary(params[:trip_id]) end else # No permission if @invitation_code flash[:notice] = "Ooops! Your invitation code seems incorrect. Please double check the code with the owner." else flash[:notice] = "Ooops! Your account does not have permission to view this trip or itinerary. Please contact the owner of the trip to get a valid link to this page." end session[:previous_url] = request.fullpath render "no_permission" end else session[:previous_url] = request.fullpath flash[:notice] = "Ooops! You do not have permission to view this page. Please sign up or log in." render "devise/registrations/new" end rescue flash[:error] = "This trip does not exist." redirect_to(root_path) end end def new if !current_user # need to log in here session[:additional] = params redirect_to new_user_session_path else create_and_save_trip end end def create_and_save_trip params[:destination] = params[:destination].titleize city = params[:destination] has_trip = false @trip_id_list = [] UserTrip.where(user_id: current_user.id).each do |user_trip| @trip_id_list.append(user_trip.trip_id) end @trips = Trip.where(id: @trip_id_list) @trips.each do |trip| if trip.city == city has_trip = true break end end if params[:startdate].include? "/" start_lst = params[:startdate].split("/") end_lst = params[:enddate].split("/") start_time = DateTime.new(start_lst[2].to_i, start_lst[0].to_i, start_lst[1].to_i, 0, 0, 0) end_time = DateTime.new(end_lst[2].to_i, end_lst[0].to_i, end_lst[1].to_i, 0, 0, 0) else start_lst = params[:startdate].split("-") end_lst = params[:enddate].split("-") start_time = DateTime.new(start_lst[0].to_i, start_lst[1].to_i, start_lst[2].split(" ")[0].to_i, 0, 0, 0) end_time = DateTime.new(end_lst[0].to_i, end_lst[1].to_i, end_lst[2].split(" ")[0].to_i, 0, 0, 0) end if has_trip trip = @trips.where(:city => city).first #making assumption this user only go to this city once trip.update_attributes(:start_time => start_time, :end_time => end_time) saved = trip.save else trip = Trip.new(city: city, start_time: start_time, end_time: end_time, user_id: current_user.id, uuid: SecureRandom.uuid) saved = trip.save end if saved UserTrip.create(user_id: current_user.id, trip_id: trip.id) if has_trip params.each do |key, value| if key.to_i.to_s == key trip_attraction = trip.trip_attractions.where(:attraction_id => key).first user_vote = current_user.votes.where(trip_attraction_id: trip_attraction.id).first vote_diff = value.to_i - user_vote.vote if vote_diff != 0 user_vote.increment!(:vote, by = vote_diff) trip_attraction.increment!(:vote_count, by = vote_diff) end end end generate_itinerary(trip.id) else #add in all the trip_attractions to this trip params.each do |key, value| # if (attraction_id != "destination" && attraction_id != "startdate" && attraction_id != "enddate") if key.to_i.to_s == key newTripAttraction = TripAttraction.create(attraction_id: key, trip_id: trip.id, vote_count: value) current_user.votes.create(trip_attraction: newTripAttraction, attraction_id: key, vote: value) end end generate_itinerary(trip.id) end end end def delete TripAttraction.delete_all("trip_id = #{params[:id]}") Trip.destroy(params[:id]) redirect_to user_show_path end end
class CreateProductReviews < ActiveRecord::Migration[6.1] def change create_table :product_reviews do |t| t.string :title t.integer :rating t.boolean :published t.text :content t.integer :parent_id t.timestamps end add_reference :product_reviews, :product, index: true end end
namespace :lookup do desc "Process cached word lookup requests queued during a Wordnik API failure" task failed_words: :environment do puts "Attempting to process queued queries..." WordRequestCache.process_queued_queries end end
class AddPhotoAndAdminToUser < ActiveRecord::Migration def change add_column :users, :photo_url, :string, :default => nil add_column :users, :admin, :boolean, :default => false end end
class AddTransformatorToTrparams < ActiveRecord::Migration[5.0] add_column :trparams, :transformator_id, :integer add_foreign_key :trparams, :transformators add_index :trparams, :transformator_id end
class WorkItemSerializer < ActiveModel::Serializer attributes :id, :user_id, :task, :start_time, :end_time, :description end
class Catalog < ActiveRecord::Base attr_accessible :drop_date, :name, :initial_page_count, :size has_many :pages, :as => :book, :dependent => :destroy after_save :create_catalog_pages private def create_catalog_pages order = 1 self.initial_page_count.times do page = self.pages.new page.order = order page.section_name = "Page #{order}" page.save order += 1 end end end
# base on Oink::InstanceTypeCounter module MongoDbLogger def self.extended_active_record? @oink_extended_active_record end def self.extended_active_record! @oink_extended_active_record = true end module InstanceCounter def self.included(klass) if Rails.logger && Rails.logger.respond_to?(:add_metadata) ActiveRecord::Base.send(:include, MongoDbLoggerInstanceCounterInstanceMethods) klass.class_eval do after_filter :report_instance_type_count end end end def before_report_active_record_count(instantiation_data) end private def report_instance_type_count report_hash = ActiveRecord::Base.instantiated_hash.merge("Total" => ActiveRecord::Base.total_objects_instantiated) Rails.logger.add_metadata(:instance_counter => report_hash) ActiveRecord::Base.reset_instance_type_count end end module MongoDbLoggerInstanceCounterInstanceMethods def self.included(klass) klass.class_eval do @@instantiated = {} @@total = nil def self.reset_instance_type_count @@instantiated = {} @@total = nil end def self.instantiated_hash @@instantiated end def self.total_objects_instantiated @@total ||= @@instantiated.inject(0) { |i, j| i + j.last } end unless MongoDbLogger.extended_active_record? if instance_methods.include?("after_initialize") def after_initialize_with_oink after_initialize_without_oink increment_ar_count end alias_method_chain :after_initialize, :oink else def after_initialize increment_ar_count end end MongoDbLogger.extended_active_record! end end end def increment_ar_count @@instantiated[self.class.base_class.name] ||= 0 @@instantiated[self.class.base_class.name] = @@instantiated[self.class.base_class.name] + 1 end end end
class RemoteDeploymentsController < ApplicationController respond_to :json def index respond_with deployment_service.all end def show respond_with deployment_service.find(params[:id]) end def create override = TemplateBuilder.create(params[:override]) deployment = deployment_service.create(template: template, override: override) respond_with deployment, location: nil end def destroy respond_with deployment_service.destroy(params[:id]) end def redeploy respond_with deployment_service.redeploy(params[:id]), location: nil, status: 201 end private def deployment_service @service ||= deployment_target.new_agent_service(DeploymentService) end def deployment_target @deployment_target ||= DeploymentTarget.find(params[:deployment_target_id]) end def template resource_id = params[:resource_id] if params[:resource_type] == 'App' TemplateBuilder.create({ app_id: resource_id }, false) else Template.find(resource_id) end end end
# frozen_string_literal: true FactoryBot.define do factory :score do wakeup_on { '2019-04-28' } score { 1 } reason { 'よく寝た' } cause { '早く寝た' } user end end
require 'rspec' require_relative './lib/tictactoe.rb' require 'stringio' def capture_name $stdin.gets.chomp end RSpec.describe Tictactoe do describe '#play' do before do $stdin = StringIO.new("s\n1\n2\n3\n4\n5\n6\n7\n8\n9") end after do $stdin = STDIN end context 'It a base of tictacgame' do it 'this method have a test winner' do game = Tictactoe.new game.play end end end end
class AddProductVarientsToSpreeVariants < ActiveRecord::Migration def change add_column :spree_variants, :expireable, :boolean add_column :spree_variants, :pestissue, :boolean add_column :spree_variants, :multiplebarcode, :boolean end end
require 'cucumber/rspec/doubles' Given(/^I am on the home page$/) do visit('/') end When(/^I enter "([^"]*)" in the "([^"]*)" field$/) do |text, field| fill_in(field, with: text) end Then(/^I see "([^"]*)"$/) do |text| expect(page).to have_content(text) end When(/^I press the "([^"]*)" button$/) do |button| click_button(button) end Then(/^I see "([^"]*)" with class "([^"]*)"$/) do |_text, klass| expect(page).to have_css("h1.#{klass}") end When(/^the computer chooses "([^"]*)"$/) do |move| Rps.any_instance.stub(:other_move) { move.to_sym } end When(/^I am on the "([^"]*)" page$/) do |page| visit('/' << page) end When(/^I am in (.*) browser$/) do |name| Capybara.session_name = name end When(/^(?!I am in)(.*(?= in)) in (.*) browser$/) do |other_step, name| step "I am in #{name} browser" step other_step end Then(/^I see a "([^"]*)" button$/) do |button| expect(page).to have_selector("button[value='#{button}']") end When(/^I wait (\d+) seconds$/) do |seconds| sleep(seconds.to_i) end
class UsersController < ApplicationController before_filter :authenticate_user!, :except => [:create] unless Rails.env.test? def create # Create the user from params @user = User.new(params.require(:user).permit(:name, :email, :password, :password_confirmation)) if @user.save # Deliver the signup_email # UserMailer.signup_email(@user).deliver redirect_to(@user, :notice => "User created") else render :action => "new" end end def index @users = User.all end def show @user = User.find(params[:id]) end def new @user = User.new end def edit @user = User.find(params[:id]) session[:return_to] = request.referer end def update @user = User.find(params[:id]) if @user.update_attributes(params.require(:user).permit(:name, :email, :password, :password_confirmation)) redirect_to @user, :notice => "User was successfully updated." else render :action => 'edit' end end def destroy @user = User.find(params[:id]) @user.destroy redirect_to users_path, :notice => 'User was successfully deleted.' end private def authenticate_user! super unless $disable_authentication end end
class Vocabulist < Formula desc "Personalized vocabulary frequency list for learning Japanese" homepage "https://github.com/odakaui/vocabulist" license "MIT" if OS.mac? url "https://github.com/odakaui/vocabulist/releases/download/v0.1.8/vocabulist-v0.1.8-x86_64-apple-darwin.tar.gz" sha256 "496854379ba72ef265cfd0225c17949f2bc8ecaedbf205e4df86c57b9df12eff" elsif OS.linux? url "https://github.com/odakaui/vocabulist/releases/download/v0.1.8/vocabulist-v0.1.8-x86_64-unknown-linux-gnu.tar.gz" sha256 "c1b4176879009a19f498ee8eb5a4ad9fb5a13a2abfb29f2fcc4b4056b5294b75" end depends_on "mecab" => :recommended depends_on "mecab-ipadic" => :recommended def install bin.install "vocabulist_rs" pkgshare.install "jmdict.db" prefix.install "ACKNOWLEDGEMENTS.md" end def caveats <<~EOS If you do not have an existing config file, you will need to create one before you can start using vocabulist_rs. Please run `vocabulist_rs config --homebrew`. EOS end test do system bin/"vocabulist_rs", "config" assert_predicate testpath/".vocabulist_rs/config.toml", :exist? end end
module Report attr_reader :report def patient Patient.find(patient_id) end def header address = %(\n#{Date.today.strftime('%m %B %Y')}\n\n#{patient.address_line_1 unless patient.address_line_1.blank?}) [patient.address_line_2, patient.address_line_3].each do |line| address += %(\n#{line}) unless line.blank? end address += %(\n#{patient.city}, #{patient.state} #{patient.country}\n#{patient.postal_code}) greeting = %(\nTo whom it may concern, \nI had the pleasure of meeting #{patient.first_name} in Atlanta at the 33rd annual Marfan Foundation Conference in Atlanta, GA on August 3rd and 4th, 2017 in clinic for a comprehensive patient assessment.) %(#{address} #{greeting}) end def vitals_paragraph vitals = self.vitals phrases = [] phrases << "a blood pressure of #{vitals.select { |v| v.topic.name == 'blood pressure' }[0].measurement}" if vitals.select { |v| v.topic.name == 'blood pressure' }[0] phrases << "a pulse of #{vitals.select { |v| v.topic.name == 'heart rate' }[0].measurement}" if vitals.select { |v| v.topic.name == 'heart rate' }[0] phrases << "a height of #{vitals.select { |v| v.topic.name == 'height' }[0].measurement.to_f.round(2)}m" if vitals.select { |v| v.topic.name == 'height' }[0] phrases << "a weight of #{vitals.select { |v| v.topic.name == 'weight' }[0].measurement.to_f.round(2)}kg" if vitals.select { |v| v.topic.name == 'weight' }[0] phrases << "a temperature of #{vitals.select { |v| v.topic.name == 'temperature' }[0].measurement.to_f.round(1)}°C" if vitals.select { |v| v.topic.name == 'temperature' }[0] if phrases.empty? summ = %(#{patient.first_name} had no vitals measured during this visit.) else summ = %(#{patient.first_name} was in good health when I saw #{patient.object_pronoun} with #{list_constructor(phrases)}.) end summ end def family_paragraph patient = Patient.find(patient_id) family_members = patient.family_members if family_members.blank? %(A family history was not completed for #{patient.first_name} during #{patient.possessive_pronoun} visit.) else bios = "" family_members.each do |fm| bios += "\n#{fm.generate_full_summary} " end %(As part of #{patient.first_name}'s comprehensive visit we gathered the following family history: #{bios}) end end def meds_paragraph patient = Patient.find(patient_id) meds = patient.medications.select(&:current?) discont = patient.medications.select { |m| m.current === false } if meds.blank? summ = %(I did not discuss any medications with #{patient.first_name} during our visit.) else all_meds = meds.map(&:generate_full_summary) summ = %(#{patient.first_name.capitalize}'s medications consist of:\n• #{list_constructor(all_meds, '', "\n• ")}) end summ end def imagery_paragraph visit = self patient = Patient.find(visit.patient_id) if !visit.heart_measurements.empty? paragraph = 'The following heart imagery was gathered as part of our visit: ' results = list_constructor(visit.heart_measurements.map(&:generate_summary)) + "." paragraph += results else paragraph = "No heart measurements were taken of #{patient.first_name} as part of our visit." end paragraph end ## Concerns = anything discussed in a visit not incl: family history, vitals, heart imagery, meds. def concerns_body patient = Patient.find(patient_id) concerns = letter_sort_by_topic body = '' no_instances = [] concerns.each do |topic, instances| if instances.blank? no_instances << topic else body << "\n#{patient.first_name} had #{instances.length} #{topic}: #{list_constructor(instances.map(&:generate_full_summary))}." end end "#{body} \n#{patient.first_name} reported no #{list_constructor(no_instances, 'nor')}." end def recommendations patient = Patient.find(patient_id) recs = '' if patient.medications continue = patient.medications.select(&:current?) discontinue = patient.medications.select { |m| m.current === false } unless continue.empty? summ = list_constructor(continue.map(&:generate_full_summary), '', ";\n• ") recs << "We advise #{patient.first_name} continue to take:\n• #{summ};" end unless discontinue.empty? summ = list_constructor(discontinue.map(&:generate_summary), '', ";\n• ") recs << "\nWe advise him to discontinue taking:\n• #{summ};" end end if genetic_tests genetic_tests.each do |test| if test.predictive_testing_recommended === true recs << %(\n\nBased on #{patient.possessive_pronoun} genetic test results for #{test.topic.name} and the risk factors we discussed, we recommend that #{patient.first_name} undergo predictive genetic testing.) end end end summ = recs.blank? ? 'We have no recommendations for further care at this time.' : recs %(#{summ}) end def signature %(I have assured #{patient.first_name} that the whole clinic team will be available to #{patient.object_pronoun} in case there are any issues that arise in the future. I encouraged #{patient.object_pronoun} to contact me if #{patient.subject_pronoun} has any problems with or is intolerant of any changes we recommended. \nIt has been a pleasure to participate in #{patient.first_name.capitalize}'s care. If there are any questions or concerns, please don't hesitate contact us. \nSincerely, \n#{clinician.first_name} #{clinician.last_name} \n#{clinician.practice_name}) end def report %(#{header} \n#{vitals_paragraph} \n#{meds_paragraph} \n#{imagery_paragraph} \n#{family_paragraph} \n#{concerns_body} \n#{recommendations} \n#{signature}) end end
class CreateUsuarios < ActiveRecord::Migration def change create_table :usuarios do |t| t.string :nome t.string :cpf t.string :telefone t.string :email t.string :login t.string :senha t.boolean :ativo t.boolean :gerente t.index :cpf, unique: true t.index :email, unique: true t.index :login, unique: true t.timestamps null: false end end end
# TODO: # - Table of Contents require 'net/http' require 'json' module ApiDump Version = "1.0.0.5" BuildDate = "190430a" CrLf = 13.chr + 10.chr class ApiRequest attr_accessor :url, :http_method, :output, :headers, :params def initialize(url, http_method, params = nil, headers = nil) @url = url @http_method = http_method @params = params @headers = headers end def send_request(uri) uri = URI(uri) rsp = nil Net::HTTP.start(uri.host, uri.port) do |http| if http_method.downcase == "post" req = Net::HTTP::Post.new(uri, @headers) else req = Net::HTTP::Get.new(uri, @headers) end req.body = @params.to_json if @params rsp = http.request req end rsp end def execute send_request(@url) end end class HtmlOutputFormatter def initialize(title, version = "", build_date = "") @title = title @version = version @build_date = build_date end def header(extra = "") i1 = !@version.empty? ? "Version <b>#{@version}</b>" : "" i2 = !@build_date.empty? ? "Build Date <b>#{@build_date}</b>" : "" vi = vi = !i1.empty? || !i2.empty? ? " #{[i1, i2].join(" ")}<br/><br/>" : "" <<EOS <html> <head> <title>#{@title}</title> <style> body, td { font-family: Verdana; font-size: 12px; } h1 { font-size: 14px; } h2 { font-size: 13px; } h3 { font-size: 12px; } h4 { font-size: 11px; } h5 { font-size: 10px; } h6 { font-size: 9px; } pre { font-family: Courier New; font-size: 12px; margin-top: 6px; margin-bottom: 0px; } .title { width: 100%; padding: 4 4 4 4; font-size: 12px; font-weight: bold; background-color: #000000; color: #ffffff; } table.api_info { cell-spacing: 0; cell-padding: 0; border-collapse: collapse; width: 100%; margin-top: 8px; table-layout: fixed; } table.api_info td { vertical-align: top; word-wrap: break-word; } .name { font-family: Arial; Tahoma; color: #c000c0 } .mandatory { color: #c00000; } .optional { color: #00c000; } </style> </head> <body> <a name='#top'> <h1>#{@title}</h1> #{vi}#{extra} EOS end def footer(extra = "") <<EOS #{extra} </body> </html> EOS end def format_feature_begin(feature, request_headers) pv = feature.params.values.map do |k,v| if v.downcase.index("mandatory") cc = " mandatory" elsif v.downcase.index("optional") cc = " optional" else cc = "" end "<span class='name#{cc}'>#{k}</span>: #{v}" end pv = pv.join("<br/>#{CrLf} ") pc = !feature.params.comment.empty? ? "Notes: #{feature.params.comment}" : "" <<EOS <a name = '#{feature.object_id}'> <div class="title"> # #{feature.name} </div> <table class="api_info"> <tr> <td width="80px">Description</td> <td width="10px">:</td> <td> #{feature.description} </td> </tr> <tr> <td>URL</td> <td>:</td> <td> #{feature.url} </td> </tr> <tr> <td>Method</td> <td>:</td> <td> #{feature.request_method.upcase} </td> </tr> <tr> <td>Headers</td> <td>:</td> <td> #{request_headers} </td> </tr> <tr> <td>Parameters</td> <td>:</td> <td> #{[pv, pc].select{|x|!x.empty?}.join("<br/>#{CrLf} ")} </td> </tr> <tr> <td>Examples</td> <td>:</td> <td> EOS end def format_feature_end <<EOS </td> </tr> </table> <br/> <a href='#top'>Back to top</a> <br/><br/> EOS end def format_request(feature, ex_nbr, base_url, params, output = nil, error = nil) ex = feature.examples[ex_nbr] tt = !ex.title.empty? ? ex.title : "Example: #{ex_nbr}".strip <<EOS <a name='#{ex.object_id}'> <h2>#{tt}</h2> URL:<br/>#{base_url}#{ex.url}<br/> <br/> Parameters:<br/> <pre> #{JSON.pretty_generate(params)} </pre> <br/> Output:<br/> <pre>#{output ? output : "Error: #{error}"}</pre> <br/> EOS end def result(info = "") if !info.empty? " <hr/>#{CrLf}#{info}" else "" end end end class FeatureParam attr_accessor :values, :comment def initialize(options = {}) @values = options.fetch(:values, {}) @comment = options.fetch(:comment, "") end end class ApiExample attr_accessor :example_id, :title, :comment, :url, :params, :input, :output attr_reader :before, :after def initialize(owner = nil, options = {}) @owner = owner @example_id = options.fetch(:id, :"") @title = options.fetch(:title, "") @comment = options.fetch(:comment, "") @url = options.fetch(:url, "") @params = options.fetch(:params, {}) @input = options.fetch(:input, {}) @output = options.fetch(:output, {}) @before = options.fetch(:before, nil) @after = options.fetch(:after, nil) end end class ApiFeature attr_accessor \ :name, :description, :request_method, :request_type, :url, :params, :examples def initialize(options = {}) @name = options.fetch(:name, "") @description = options.fetch(:description, "") @request_method = options.fetch(:method, "GET") @request_type = options.fetch(:request_type, "JSON") @url = options.fetch(:url, "") @params = FeatureParam.new(options.fetch(:params, {})) @examples = options.fetch(:examples, []).map{|x|ApiExample.new(self, x)} end end class Specification attr_accessor \ :title, :version, :date, :header, :footer, :base_url, :output_format, :features def initialize @title = "" @version = "" @date = "" @header = "" @footer = "" @base_url = "" @output_format = "" @features = [] yield(self) if block_given? end def base_url=(data) if !(bu = data.strip).empty? bu.chop if bu[-1] == "/" end @base_url = bu end def features=(data) @features = data.map{|f|ApiFeature.new(f)} end def self.load(spec_file) instance_eval File.read(spec_file), spec_file end end class Generator attr_reader :spec, :succ_count, :fail_count private def initialize(spec) @spec = spec @output_file = nil @formatter = nil @succ_count = 0 @fail_count = 0 @results = {} end def getterproc(a) n = a.split("/") Proc.new do |x| n.map{|x|x.gsub("%slash%", "/")}.inject(x) do |a, b| if (!Integer(b).nil? rescue false) a[b.to_i] elsif b[0] == ":" a[b[1..-1].to_sym] else a[b] end end rescue end end def write_header(extra = "") if !(hh = @formatter.header(extra)).empty? @output_file.write hh end end def write_result(info = "") if !(rr = @formatter.result(info)).empty? @output_file.write rr end end def write_footer(extra = "") if !(ff = @formatter.footer(extra)).empty? @output_file.write ff end end def write_toc cc = @spec.features.map do |f| if f.examples.count == 0 "" elsif f.examples.count == 1 ex = f.examples.first tt = !ex.title.empty? ? ex.title : "Example 1" " <a href='##{f.object_id}'>#{f.name}</a>" \ " - " \ "<a href='##{ex.object_id}'>#{tt}</a>#{}</a><br/>" else ee = (0...(f.examples.count)).map do |i| e = f.examples[i] en = !e.title.empty? ? e.title : "Example #{i}" " <li><a href='##{e.object_id}'>#{en}</a></li>#{CrLf}" end " <a href='##{f.object_id}'>#{f.name}</a><br/>#{CrLf}" \ " <ul>#{CrLf}" \ "#{ee.join}" \ " </ul>" end end @output_file.write( " #{CrLf}" \ " <div class='title'>Table of Contents</div>#{CrLf}" \ " <br/>#{CrLf}" \ "#{cc.select{|x|!x.empty?}.join("#{CrLf}")}" \ " #{CrLf}" \ " <br/><br/>#{CrLf}" \ " <a href='#top'>Back to top</a>" \ " <br/><br/>#{CrLf} #{CrLf} #{CrLf}" ) end def start_feature(feature, req_headers) @output_file.write @formatter.format_feature_begin(feature, req_headers) end def end_feature @output_file.write @formatter.format_feature_end end def write_request(feature, ex_nbr, request) suc = false exp = feature.examples[ex_nbr] rsp = nil txt = nil dat = nil err = nil begin rsp = request.execute rescue Exception => ex if ex.is_a?(Interrupt) raise ex else err = "Error: #{ex.message}" end end if rsp.nil? err = !err.empty? ? err : "Response is NULL." elsif (stt = rsp.response.code) == "404" err = "URL not found (404)." elsif stt == "500" err = "Internal server error (500)." elsif stt != "200" err = "Unexpected response (#{rsp.class}): #{stt}." elsif (body = rsp.body).nil? err = "Response body is NULL." elsif (dat = JSON.parse(body)).nil? err = "Response is not a valid JSON." elsif (code = dat.fetch("code", nil)).nil? err = "JSON field 'code' not found." elsif code != 0 err = "# Error: #{dat.fetch("desc", "(Error description is not available)")}" txt = body else @results[exp.example_id] = dat suc = true txt = body end if suc puts "#{exp.url} => #{stt}" @succ_count += 1 else inf = err.length > 77 ? err.gsub("\n", "\\\\n")[0..77] + "..." : err puts "#{exp.url} => #{rsp.class}#{CrLf}#{inf}" @fail_count += 1 end @output_file.write( @formatter.format_request( feature, ex_nbr, @spec.base_url, request.params, txt, err ) ) dat end public def start(out_file) @output_file = File.new(out_file, "wb") @formatter = HtmlOutputFormatter.new(@spec.title, @spec.version, @spec.date) req_headers = {"Content-Type" => "application/json"} write_header \ "#{CrLf} #{CrLf} " \ "Generated on #{Time.new.strftime("%Y-%m-%d %H:%M:%S")} " \ "using API Dump v#{Version} Build #{BuildDate}#{CrLf}" \ "#{@spec.header} " write_toc @spec.features.each do |feature| start_feature feature, req_headers (0...feature.examples.count).each do |i| rq = feature.examples[i] ip = {} rs = nil en = {results: @results, request: rq} rq.before.call(en) if rq.before if rq.input.is_a?(Hash) rq.input.keys.each do |k| ip[k] = getterproc(rq.input[k]).call(@results) end end rs = write_request( feature, i, ApiRequest.new( "#{@spec.base_url}#{rq.url}", feature.request_method, ip.merge(rq.params.is_a?(Hash) ? rq.params : {}), req_headers ) ) rq.after.call(en) if rq.after if rq.output.is_a?(Hash) @results[rq.example_id] = rq.output.keys.inject({}) do |a,b| a[b] = getterproc(rq.output[b]).call(rs); a end end end end_feature end write_result \ " " \ "Total #{@spec.features.count} features, " \ "#{@succ_count + @fail_count} requests, #{@succ_count} success, " \ "#{@fail_count} errors." write_footer @spec.footer puts puts "Total #{@succ_count + @fail_count} request executed, #{@succ_count} success, #{@fail_count} errors." puts puts "Output file: #{out_file}" end end end args = ARGV puts "API Dump v#{ApiDump::Version} Build #{ApiDump::BuildDate}" puts "Written by Heryudi Praja (mr_orche@yahoo.com)" puts "This app is licensed under MIT" puts if !(1..2).include?(args.count) puts "Usage: ruby #{__FILE__} config_file [output_file]" elsif !File.exist?((cf = args[0])) puts "Apispec \"#{cf}\" doesn't exist." else if args.count == 2 ofn = args[1] else (ofn = "#{args[0]}")[(-File.extname(args[0]).length)..-1] = ".html" end gen = ApiDump::Generator.new(ApiDump::Specification.load(args[0])) gen.start ofn end
class AddColumnToUserReply < ActiveRecord::Migration def change add_column :user_replies, :follow_up_cycle_email, :text end end
class UrbanProjectsController < ApplicationController def index @urban_projects = UrbanProject.all end end
# # == Schema Information # # Table name: genres # # id :integer not null, primary key # name :string # created_at :datetime not null # updated_at :datetime not null # external_id :integer # # frozen_string_literal: true require 'rails_helper' RSpec.describe Genre, type: :model do describe '.create' do it 'should create new genre record' do expect do Genre.create(name: 'genre', external_id: 1) end.to(change { Genre.count }) end %i[name external_id].each do |field| it { should validate_presence_of(field) } end end end
require 'rubygems' require './app.rb' namespace :assets do # desc 'compile assets' task :compile => [:compile_js, :compile_css] do end # desc 'compile javascript assets' task :compile_js do sprockets = App.settings.sprockets asset = sprockets['application.js'] outpath = File.join(App.settings.assets_path, 'js') outfile = Pathname.new(outpath).join('application.min.js') # may want to use the digest in the future? FileUtils.mkdir_p outfile.dirname asset.write_to(outfile) asset.write_to("#{outfile}.gz") puts "successfully compiled js assets" end # desc 'compile css assets' task :compile_css do sprockets = App.settings.sprockets asset = sprockets['application.css'] outpath = File.join(App.settings.assets_path, 'css') outfile = Pathname.new(outpath).join('application.min.css') # may want to use the digest in the future? FileUtils.mkdir_p outfile.dirname asset.write_to(outfile) asset.write_to("#{outfile}.gz") puts "successfully compiled css assets" end # todo: add :clean_all, :clean_css, :clean_js tasks, invoke before writing new file(s) end namespace :storage do task :create do Dir["#{App.settings.root}/models/*.rb"].each do |file| model_name = File.basename(file, ".*") storage_file_path = case ENV["RACK_ENV"] when "production" "#{App.settings.root}/storage/production/#{model_name.pluralize}.yml" when "test" "#{App.settings.root}/storage/test/#{model_name.pluralize}.yml" else "#{App.settings.root}/storage/#{model_name.pluralize}.yml" end dirname = File.dirname(storage_file_path) unless File.directory?(dirname) FileUtils.mkdir_p(dirname) end next if model_name == "base_model" next(puts "Skip #{model_name}.yml") if File.exist?(storage_file_path) puts "creating #{model_name}.yml" FileUtils.touch(storage_file_path) puts "done." end end end
require "spec_helper" describe UserMailer do # describe "Registration Confirmation mail" do # let(:mail) { UserMailer.registration_confirmation(user) } # it { expect(mail.to).to have_content("#{user.email}") } # it { expect(mail.subject).to eq(full_title("Registration Confirmation for #{ user.name }")) } # it { expect(mail.body.encoded).to have_link('Check it Out', href: user_url(user)) } # pending "Body: confirm signup link must point to a activate user controller#action" # pending "To: address test needs refining to include \"name <email>\" syntax" # end describe "account_activation" do let(:user) { FactoryGirl.create(:user) } let(:mail) { UserMailer.account_activation(user) } it "To: shoud have expected format" do expect(mail.to).to have_content("#{user.email}") end it "Subject: field should have expected text" do expect(mail.subject).to eq(full_title("Activation Required for #{ user.name }")) end it "Body: should have Activate Link" do expect(mail.body.encoded).to have_link('Activate', href: edit_account_activation_url(user.activation_token, email: user.email)) end it "Body: should greet user by name" do expect(mail.body.encoded).to have_content("Hi #{user.name}") end end describe "password_reset" do let(:user) { FactoryGirl.create(:user) } before do user.create_reset_digest end after do user.destroy! # TODO find way to NOT have to explicitly delete test record end describe "for one user" do let(:mail) { UserMailer.password_reset(user) } it "From: " do expect(mail.from).to have_content("rortestmailer@gmail.com") end it "To: shoud have expected format" do expect(mail.to).to have_content("#{user.email}") end it "Subject: field should have expected text" do expect(mail.subject).to eq(full_title("Password reset requested for #{user.name}")) end it "Body: should have reset Link" do expect(mail.body.encoded).to have_link("reset", href: edit_password_reset_url(user.reset_token,email: user.email)) end it "Body: should greet user by name" do expect(mail.body.encoded).to have_content("Hi #{user.name}") end end end end
class CreateSpecimenGroupRelationships < ActiveRecord::Migration def change create_table :specimen_group_relationships do |t| t.references :specimen, index: true, foreign_key: true t.references :specimen_group, index: true, foreign_key: true t.timestamps null: false end end end
#!/usr/bin/env ruby -wKU # Prints out the infomation about playcounts from a specifed YAML file # Bilal Syed Hussain require "yaml" require "pp" require 'trollop' Sorts = { name: -> k,v { k } , tracks: -> k,v { -v[:total_tracks]} , creation: -> k,v { v[:creation]} , plays: -> k,v { -v[:total_count]} , finished: -> k,v { -v[:played].to_f/v[:total_tracks].to_f} } YAML_FILE =File.expand_path "~/Music/playcount.yaml" DIR_LOCATION="/Users/bilalh/Movies/add" require 'open3' require 'time' def creation_time(file) t=Open3.popen3("mdls", "-name", "kMDItemFSCreationDate", "-raw", file)[1].read result = nil begin result =Time.parse(t) rescue Exception => e result =nil end return result end # option parser ops = Trollop::options do opt :name , "Sort by name" opt :tracks , "Sort by total tracks" opt :creation , "Sort by creation date" opt :plays , "Sort by play counts" opt :finished , "Sort by percents played" opt :all , "Shows all Folders in Directory" end sorter = Sorts[:name] Sorts.each_key do |k| if ops[k] then sorter = Sorts[k] break end end hash = YAML::load File.open YAML_FILE # Getting the data arr=hash.to_a.map do |e| [e[0].gsub(%r{/Users/bilalh/Movies/add/}, '') .gsub(%r{^./}, ''),e[1]] end.sort albums = {} arr.each do |track| name = track[0][/(.*?)\//,1] album = albums[name] || {total_count:0, total_tracks:0,played:0} album[:total_count] += track[1] if album[:total_tracks] = 0 then album[:total_tracks] = Dir["#{DIR_LOCATION}/#{name}/**/*{mp3,m4a,flac}"].length album[:creation] = creation_time("#{DIR_LOCATION}/#{name}") end album[:played]+=1 albums[name] = album end if ops[:all] then Dir["#{DIR_LOCATION}/*/"].each do |f| name = File.basename f unless albums.has_key? name count = Dir["#{DIR_LOCATION}/#{name}/**/*{mp3,m4a,flac}"].length albums[name] = {total_count:0, total_tracks:count,played:0, creation:creation_time("#{DIR_LOCATION}/#{name}")} end end end # Printing printf "%-51s %4s %4s %3s %s\n", "Album", "Tracks", "Plays", "Played?", "Date" albums.sort_by { |k,v| sorter[k,v] }.each do |e| album = e[0] values = e[1] printf "%-54s %3d %5d %-7s %s\n", album, values[:total_tracks], values[:total_count], (values[:played] ==values[:total_tracks]) ? "Yes" : "%3d/%-3d" % [values[:played],values[:total_tracks]], values[:creation] ? values[:creation].strftime('%b %d') : "Deleted" end
class AddPlaidIdToCategory < ActiveRecord::Migration def change add_column :categories, :plaid_id, :string, index: true end end
class Customer attr_reader :name attr_reader :date_of_birth attr_reader :rentals attr_reader :address def initialize(name, date_of_birth, address) @name = name @date_of_birth = date_of_birth @rentals = [] @address = address end def add_rental(movie) @rentals << movie end def summary "#{@name}, #{@address.house} #{@address.street}, #{@address.city}, #{@address.state} #{@address.zipcode}" end def statement total_amount, frequent_renter_points = 0, 0 result = "Rental Record for #{@name}\n" @rentals.each do |element| this_amount = 0 case element.rating when Rating::G this_amount += 2 when Rating::PG this_amount += 3 when Rating::PG13 this_amount += 3.5 when Rating::R this_amount += 1 end #add frequent renter points frequent_renter_points += element.frequent_renter_points #show figures for this rental result += '\t' + element.title + '\t' + element.charge.to_s + '\n' total_amount += element.charge end #add footer lines result += "Amount owed is #{total_amount}\n" result += "You earned #{frequent_renter_points} frequent renter points" result end def html_statement total_amount, frequent_renter_points = 0, 0 result = "<h2>Rental Record for #{@name}</h2>" result += "<table>" @rentals.each do |element| this_amount = 0 case element.rating when Rating::G this_amount += 2 when Rating::PG this_amount += 3 when Rating::PG13 this_amount += 3.5 when Rating::R this_amount += 1 end #add frequent renter points frequent_renter_points += element.frequent_renter_points #show figures for this rental result += '<tr><td>' + element.title + '</td><td>' + element.charge.to_s + '</td></tr>' total_amount += element.charge end result += '</table>' #add footer lines result += "<h3>Amount owed is #{total_amount}</h3>" result += "<h4>You earned #{frequent_renter_points} frequent renter points</h4>" result end end
def shuffled_shoe(number_of_decks = 6) # Returns a "shoe" array filled with 312 shuffled "card" arrays, each with a value and suit. deck_of_values = [] # A place in which to repeatedly collect the thirteen card values. deck_of_suits = [] # A place in which to establish thirteen instances of each suit. 4.times do # For each of the four suits, (1..13).map do |c| # count out thirteen cards. if c == 1 # Make the first one deck_of_values.push("A") # an ace. elsif c <= 10 # Make the next nine of them deck_of_values.push(c.to_s) # the same value as their count order. elsif c == 11 # Make the eleventh one deck_of_values.push("J") # a Jack. elsif c == 12 # Make the twelfth one deck_of_values.push("Q") # a Queen. elsif c == 13 # Make the thirteenth one deck_of_values.push("K") # a King. end end end 13.times do deck_of_suits << "C" end # Make thirteen Clubs in a row. 13.times do deck_of_suits << "D" end # Make thirteen Diamonds in a row. 13.times do deck_of_suits << "H" end # Make thirteen Hearts in a row. 13.times do deck_of_suits << "S" end # Make thirteen Spades in a row. deck_of_cards = deck_of_values.zip(deck_of_suits) # Assign suits to the four groups of cards. pile = [] # Establish a pile in which to shuffle together multiple decks. number_of_decks.times { deck_of_cards.each { |deck| pile.push(deck) } } # Put decks of unboxed cards in a pile. stack = pile.shuffle! # Shuffle together all cards from all decks. puts "Would you like to cut the deck?" if gets.strip[0]&.downcase == y puts "About how many cards would you like to take off the top?" cut = gets.strip.to_i - 5 + rand(10) ##give player option to cut ##insert shuffle card 60-75 cards from bottom end class Shoe def instantiate(decks) @shoe = shuffled_shoe(decks) end def deal dealt_card = @shoe.pop shoe = shuffled_shoe def valid_bet?(bet) bet.between?(2, 500) && bet < def betting puts "Bet?" print "$" bet = gets.strip if valid_bet?(bet)
version = node[:vim][:version] comp_opts = node[:vim][:compile_opts].join(' ') Chef::Log.info("Compiling vim version #{version}") Chef::Log.info("Compile options are #{comp_opts}") scripts = %w(libperl-dev python-dev) if node[:vim][:rubycompiled] Chef::Log.info("Ruby headers already present") else Chef::Log.info("Adding Ruby headers to dependancies") scripts << "ruby-dev" end depends = %w(libncurses5-dev libgnome2-dev libgnomeui-dev libgtk2.0-dev libatk1.0-dev libbonoboui2-dev libcairo2-dev libx11-dev libxpm-dev libxt-dev) (depends + scripts).each do |d| package d end # setup a directory for the source src_dir = "/tmp/src/vim" (["/tmp/src"] << src_dir).each do |d| directory d do action :create end end archive = "vim-#{version}.tar.bz2" cookbook_file "#{src_dir}/#{archive}" do source archive mode "0666" end archive_dir = "#{src_dir}/vim#{version.gsub('.', '')}" execute "extract vim archive" do command "tar xjf #{archive}" cwd src_dir creates archive_dir user "root" end vim_src = "#{archive_dir}/src" log = "#{src_dir}/make.log" # find way to not recompile if correct version and compiled by chef cmds = [] cmds << "./configure #{comp_opts} 2>&1 | tee #{log}" cmds << "make 2>&1 | tee -a #{log}" cmds << "make install 2>&1 | tee -a #{log}" cmds.each do |cmd| execute cmd do cwd vim_src user "root" end end # add the icon cookbook_file "/usr/share/pixmaps/gvim.png" do source "gvim.png" owner "root" group "root" mode "0644" end # and the desktop file cookbook_file "/usr/share/applications/gvim.desktop" do source "gvim.desktop" owner "root" group "root" mode "0644" end
class ArtistBalance < ApplicationRecord belongs_to :artist validates :artist_id, numericality: {message: "%{value} Debe ser el ID de un Artista."} validates :balance, numericality: {message: "%{value} Debe ser un decimal."} end
json.array!(@datos) do |dato| json.extract! dato, :id, :fullname, :phone, :direccion json.url dato_url(dato, format: :json) end
#--------------------------------------------------------------- # 3.9 Exercises # 1. You saw that Ruby does not allow addition of floats and strings. What type combinations does Ruby allow to be added? puts "Integers & Floats, Strings & Strings, Integers & Integers" # 2. Using irb , initialize three variables, x , y , and z , each to some number less than 10. # Design an equation with these variables using at least one multiplication, one di‐ # vision, and one addition or subtraction element. Have the computer do it once # without parentheses, and then add parentheses to the equation and try it again. Are # the answers the same? If not, why not? # They aren't necessarily the same because parenthesis can override default order of operations. # 3. Earlier in the chapter, we saw the following: #irb(main):001:0> 1.0 * 5 / 2 # => 2.5 # Now, try typing the following code into irb : # irb(main):002:0> 5 / 2*1.0 # This should have produced a value of 2.0. Why does it produce the value 2.0, and # not 2.5, like we saw earlier? puts "Because 5/2 is evaluated first." # 4. Write the expected value of x after both lines are executed. # a. irb(main):001:0> x = 9 # irb(main):002:0> x = x/2 puts "x = 4" # b. irb(main):003:0> x = 9 # irb(main):004:0> x = x/2.0 puts "x = 4.5" # 5. What is the expected result of c for each code group? # a. irb(main):001:0> a = Math.sqrt(9) # irb(main):002:0> b = 2 # irb(main):003:0> c = a/b puts "c = 1.5 - Math.sqrt() converts the result to a float" # b. irb(main):001:0> a = 5 # irb(main):002:0> b = 2 # irb(main):003:0> c = a/b puts "c = 2" # 6. Suppose a program finds the average temperature for a given year. A user of the # program is prompted to enter the average temperature values for each season of # the year: winter, spring, summer, and fall. The program stores these values as floats # in variables temp_winter , temp_spring , temp_summer , and temp_fall , respectively. # # The final result is stored in the variable avg_temp . The program calculates the aver‐ # age temperature with the following line: # avg_temp = temp_winter + temp_spring + temp_summer + temp_fall/4 # However, when the program runs, the value of avg_temp is always incorrect. Briefly # describe what is wrong with this line and what changes you would make to correct # this error. puts "The value is not the average because division is not being done on the sum of the values, it is being done on the temp/fall" puts "Fix: put the values to sum in parenthesis and then divide" # 7. What is the difference between logic and syntax errors? Give an example of each. puts "Logic errors don't necessarily cause the Ruby interpreter to throw errors where syntax errors do. Your logic can be right and your syntax wrong and vice-versa" puts "Logic Error ex: The previous question has an example of a logic error that does not produce the desired result." puts "Syntax Error ex: x = 1 + 'blam'"
require 'helper' class TestFarmActivity < Minitest::Test def build_fields(fields) fields.map do |field_hash| Field.new.tap do |field| field.grow(field_hash[:crop], field_hash[:time]) if field_hash[:crop] end end end def test_field_collection fields = [Field.new] farm_activity = FarmActivity.new(fields: fields) assert_equal(1, farm_activity.fields.size) end def test_add_more_field farm_activity = FarmActivity.new farm_activity.fields << Field.new assert_equal(1, farm_activity.fields.size) end def test_blank_fields field = Field.new farm_activity = FarmActivity.new(fields: [field]) assert_equal(field, farm_activity.blank_fields.first) end def test_collectable_fields fields = build_fields([ {crop: Wheat.new, time: Time.now}, {} ]) farm_activity = FarmActivity.new(fields: fields) assert_equal(fields[0], farm_activity.collectable_fields.first) end def test_harvest_fields fields = build_fields([ { crop: Wheat.new, time: Time.now - 4 * 60 } ]) farm_activity = FarmActivity.new(fields: fields) assert_equal(HarvestItem, farm_activity.harvest(fields[0]).first.class) end def test_harvest_blank_field field1 = Field.new farm_activity = FarmActivity.new(fields: [field1]) assert_equal(0, farm_activity.harvest(field1).size) end def test_harvest_field_before_harvest_time fields = build_fields([ {crop: Wheat.new, time: Time.now} ]) farm_activity = FarmActivity.new(fields: fields) assert_equal(0, farm_activity.harvest(fields[0]).size) end def test_harvest_multiple_fields fields = build_fields([ { crop: Wheat.new, time: Time.now - 4 * 60 }, { crop: Wheat.new, time: Time.now - 4 * 60 }, {}, { crop: Wheat.new, time: Time.now }, ]) farm_activity = FarmActivity.new(fields: fields) assert_equal(2, farm_activity.harvest(*fields).size) end end
class Event < ActiveRecord::Base has_and_belongs_to_many :users has_and_belongs_to_many :search_terms has_many :messages, :limit=>10, :order=>"created desc" belongs_to :creator, :class_name => "User", :foreign_key => "creator_id" validates_presence_of :name, :on => :create, :message => "can't be blank" validates_format_of :name, :with => /^[A-Za-z0-9_ ]+$/, :on => :create, :message => "can only contain letters and numbers" validate :user_can_edit_event? validate :at_least_one_search_term?, :message=>"At least one search terms is required" HUMANIZED_ATTRIBUTES = { :name => "Event Name" } def self.human_attribute_name(attr) HUMANIZED_ATTRIBUTES[attr.to_sym] || super end def Event.filter_hash(event_name) event_name.slice!(0) if event_name[0,1] == '#' event_name end def Event.create_event(params, user) event = Event.new(params[:event]) event.creator_id = user.id params[:search_terms].each do |term| event.search_terms << SearchTerm.new({:term=>term}) end unless params[:search_terms].nil? event end private def user_can_edit_event? user = User.find_by_twitter_name(self.last_updated_by) return true end def at_least_one_search_term? errors[:base] << "At least one search term must be provided" if self.search_terms.empty? end end
require 'spec_helper' feature "Deleting mentees" do scenario "Deleting a mentee" do Factory(:mentee, :name => "My Test Mentee") visit '/' click_link "See all mentees" click_link "My Test Mentee" click_link "Delete Mentee" page.should have_content("Mentee has been deleted.") visit '/' page.should_not have_content("My Test Mentee") end end