text
stringlengths
10
2.61M
require "stock_picker.rb" require 'rspec' # Stock Picker # # Write a method that takes an array of stock prices (prices on days 0, 1, ...), and outputs the most profitable pair of days on which to first buy the stock and then sell the stock. Remember, you can't sell stock before you buy it! # describe '#stockpicker' do let(:monthdata) do days = (1..30).to_a prices = Array.new(30) {rand(1000)} days.zip(prices) end let(:naive_test) do [[1, 5], [2, 100], [3, 50]] end let(:strong_test) do [[1,80], [2,100], [3,5], [4,50], [5,60], [6,75]] end it "outputs the most profiable pair of days on which to first \n buy the stock and then sell the stock" do expect(stockpicker(naive_test)).to eq([1, 2]) end it "only returns sell days that are after buy days and it \n picks the two days with the biggest difference in prices" do expect(stockpicker(strong_test)).to eq([3, 6]) end end
module Service # encoding: utf-8 class VerifyAudit attr_reader :auditor, :user, :audit_log ACCEPTED = 2 REJECTED = 1 class << self def rejected(auditor, user, options = {}) user.accepted(build_audit_log(auditor, user, REJECTED, options)) Service::MailerService::Mailer.deliver(UserMailer, :verify_rejected, user) end def accepted(auditor, user, options = {}) user.accepted(build_audit_log(auditor, user, ACCEPTED, options)) Service::MailerService::Mailer.deliver(UserMailer, :verify_accepted, user) end protected def build_audit_log(auditor, auditable, result, options) AuditLog.create(:owner_type => OWNER_TYPE_USER, :business_id => auditable.id, :created_by => auditor.id, :result => result, :comment => options[:comment] ) end end end end
# encoding: UTF-8 # == Schema Information # # Table name: users # # id :integer not null, primary key # nom :string(255) # email :string(255) # created_at :datetime not null # updated_at :datetime not null require 'spec_helper' describe User do before (:each) do @attr = { :nom => "example", :email => "user@exemple.com", :password => "foobar", :password_confirmation => "foobar" } end it "devrait creer une nouvelle instance des attributs valides" do User.create!(@attr) end #Pour que ce test marque nous avons décommenté user.db le validate it "devrait exiger un nom" do bad_user = User.new(@attr.merge(:nom => "")) bad_user.should_not be_valid end it "devrait exiger un e-mail" do no_email_user = User.new(@attr.merge(:email => "")) no_email_user.should_not be_valid end it "devrait regeter les noms trop long 10 caracteres" do long_nom = "andres"*10 long_nom_user = User.new(@attr.merge(:nom => long_nom)) long_nom_user.should_not be_valid end it "devrait rejeter l'adresse e-mail" do adresse = %w[user@foo,com user_at_foo.org example.user@foo.] adresse.each do |adress| invalid_email_user = User.new(@attr.merge(:email => adress)) invalid_email_user.should_not be_valid end end it "devrait rejeter l'adresse e-mail double" do User.create!(@attr) user_with_duplicate_email = User.new(@attr) user_with_duplicate_email.should_not be_valid end it "devrait rejeter une adresse email invalide jusqu'a la casse" do upcased_email = @attr[:email].upcase User.create!(@attr.merge(:email => upcased_email)) user_with_duplicate_email = User.new(@attr) user_with_duplicate_email.should_not be_valid end describe "password validations" do it "devrait exiger un mot de passe" do User.new(@attr.merge(:password => "", :password_confirmation => "")). should_not be_valid end it "devrait exiger une confirmation du mot de passe qui correspond" do User.new(@attr.merge(:password_confirmation => "invalid")). should_not be_valid end it "devrait rejeter les mots de passe (trop) courts" do short = "a" * 5 hash = @attr.merge(:password => short, :password_confirmation => short) User.new(hash).should_not be_valid end it "devrait rejeter les (trop) longs mots de passe" do long = "a" * 41 hash = @attr.merge(:password => long, :password_confirmation => long) User.new(hash).should_not be_valid end end describe "password encryption" do before(:each) do @user = User.create!(@attr) end it "devrait avoir un attribut mot de passe crypte" do @user.should respond_to(:encrypted_password) end it "devrait definir le mot de passe encrypte" do @user.encrypted_password.should_not be_blank end describe "Methode has_password?" do it "doit retourner true si les mots de passe coincident" do @user.has_password?(@attr[:password]).should be_true end it "doit retourner false si les mots de passe divergent" do @user.has_password?('invalide').should be_false end end#password encryption end#password validations describe "Atrribut admin" do before (:each) do @user = User.create!(@attr) end it "devrait confirmer l'exitence de 'admin'" do @user.should respond_to(:admin) end it "ne devrait pas être un administrateur par défaut" do @user.should_not be_admin end it "devrait pouvoir devenir un administrateur" do @user.toggle!(:admin) @user.should be_admin end end describe "les associations au micro-message" do before (:each) do @user = User.create(@attr) end it "devrait avoir un attribut 'microposts'" do @user.should respond_to(:microposts) end end describe "micropost associations" do before(:each) do @user = User.create(@attr) @mp1 = Factory(:micropost, :user => @user, :created_at => 1.day.ago) @mp2 = Factory(:micropost, :user => @user, :created_at => 1.hour.ago) end it "devrait avoir un attribut `microposts`" do @user.should respond_to(:microposts) end it "devrait avoir les bons micro-messags dans le bon ordre" do @user.microposts.should == [@mp2, @mp1] end it "devrait détruire les micro-messages associés" do @user.destroy [@mp1, @mp2].each do |micropost| # Micropost.find_by_id(micropost.id).should be_nil lambda do Micropost.find(micropost.id) end.should raise_error(ActiveRecord::RecordNotFound) end end describe "État de l'alimentation" do it "devrait avoir une methode `feed`" do @user.should respond_to(:feed) end it "devrait inclure les micro-messages de l'utilisateur" do @user.feed.include?(@mp1).should be_true @user.feed.include?(@mp2).should be_true end it "ne devrait pas inclure les micro-messages d'un autre utilisateur" do mp3 = Factory(:micropost, :user => Factory(:user, :email => Factory.next(:email))) @user.feed.include?(mp3).should be_false end end end end#describe user
class AvailableMods def all Dir[File.join(mod_root_path, '*')].map do |directory| files = Dir.glob(File.join(directory, '*.xcommod'), File::FNM_CASEFOLD) next unless files.any? File.basename files.first, '.*' end.compact end def mod_root_path File.expand_path '~/Library/Application Support/Steam/steamapps/workshop/content/268500' end end
class Campaign < ApplicationRecord STATISTICS_KINDS = [:total_pledges_amount_in_dollars, :total_backers_count] DATA_CAPTURE_LEVELS = { "batch_0" => { internal_description: "Batch imported from archives csv file", internal_lot_number: 4, commit_id: "", description: "This campaign was imported from archives, missing day-to-day data tracking." }, "batch_1" => { internal_description: "Simple data, lot 1", internal_lot_number: 1, commit_id: "642e91234d77d30aca337138cb46f2606229385b", description: "This campaign features simple data tracking on backers and funding." }, "batch_2" => { internal_description: "Simple data + backers data on /community", internal_lot_number: 2, commit_id: "0f1e59727fbc7654109342b367af31b349a1af6b", description: "This campaign features simple data tracking on backers and funding, with backers countries." }, "batch_3" => { internal_description: "Simple data + backers data on /community + pledges data on /rewards, lot 3", internal_lot_number: 2, commit_id: "84c36729964724ad3061a9e11e2a6d77dc045a57", description: "This campaign features data tracking on backers and funding by pledge level, with backers countries." } } delegate :category, to: :product delegate :sub_category, to: :product extend Enumerize enumerize :data_capture_level, in: [:batch_0, :batch_1, :batch_2, :batch_3] enumerize :state, in: %w(live successful unsuccessful cancelled failed suspended), scope: true, predicates: true belongs_to :product, dependent: :destroy # The creator will be set up after new campaign being saved through scraping belongs_to :creator, optional: true # The monthly_report will be created when the month ends belongs_to :monthly_report, optional: true has_many :daily_reports, dependent: :destroy has_many :pledges, dependent: :destroy has_many :pledge_daily_reports, through: :pledges # Extract scopes into Query objects scope :active, -> { where("end_date >= ?", Date.today).not_cancelled } scope :finished, -> { where("end_date < ?", Date.today) } scope :successful, -> { where("funding_goal <= campaigns.total_pledges_amount") } scope :unsuccessful, -> { finished.where("funding_goal > campaigns.total_pledges_amount") } scope :cancelled, -> { with_state("cancelled") } scope :not_cancelled, -> { without_state("cancelled") } scope :old, -> { where(data_capture_level: :batch_0) } scope :not_old, -> { where.not(data_capture_level: :batch_0) } scope :finished_and_successful, -> { finished.successful } scope :starting_this_week, -> do week_start_date = Date.today.beginning_of_week week_end_date = Date.today.end_of_week Campaign.where(start_date: (week_start_date..week_end_date)) end scope :ending_this_week, -> do week_start_date = Date.today.beginning_of_week week_end_date = Date.today.end_of_week Campaign.where(end_date: (week_start_date..week_end_date)) end scope :latest, -> { order("campaigns.created_at desc") } scope :most_funded, -> { order("total_pledges_amount desc") } scope :most_backed, -> { order("total_backers_count desc") } # Getting one extra additional daily_report scope :to_scrape_on_day, ->(date) { not_cancelled.where("end_date >= ?", date - 1) } scope :to_scrape_today, -> { to_scrape_on_day(Date.today) } scope :without_sub_category, -> do joins(:product). merge(Product.without_sub_category) end scope :without_category, -> do joins(:product). merge(Product.without_category) end scope :for_sub_category, ->(sub_category) do joins(product: [:sub_category]). includes(product: [:sub_category]). where("sub_categories.id = #{sub_category.id}") end scope :for_category, ->(category) do joins(product: [sub_category: [:category]]). includes(product: [sub_category: [:category]]). where("sub_categories.category_id = #{category.id}") end scope :successful_top_by, ->(number, stat_kind) do unless STATISTICS_KINDS.include?(stat_kind) raise ArgumentError, "You can't use this statistic kind: #{stat_kind}.\nPlease use one of these: #{STATISTICS_KINDS.join(", ")}" end successful.order("#{stat_kind} desc").limit(number) end scope :finishing_on_month_and_year, ->(month, year) do where( 'extract(month from end_date) = ? AND extract(year from end_date) = ?', month, year ) end scope :created_before, ->(date) do where("campaigns.created_at < ?", date) end scope :between_dates, ->(lower_date, upper_date = nil) do if upper_date.nil? where("end_date > ?", lower_date) else where("end_date BETWEEN ? AND ?", lower_date, upper_date) end end scope :finishing_this_month, -> do finishing_on_month_and_year(Date.today.month, Date.today.year) end scope :with_backers_more_than, ->(count:) do where("total_backers_count > ?", count).order(total_backers_count: :desc) end scope :with_pledges_more_than, ->(count:) do where("total_pledges_amount_in_dollars > ?", count).order(total_pledges_amount_in_dollars: :desc) end scope :top_by_backers, ->(count:) do order(total_backers_count: :desc).first(count) end scope :top_by_pledges, ->(count:) do order(total_pledges_amount_in_dollars: :desc).first(count) end def compute_and_save_daily_reports_data! campaign_updated_data = Campaigns::ComputeDailyReportsDataService.new(self).call self.update(campaign_updated_data) end def finished? self.end_date < Date.today end end
require 'helper_classes' module Network module Monitor module Connection attr_accessor :checks extend self @checks = %w(ppp default host ping httping openvpn ) @vpn_config = Dir.glob('/etc/openvpn/*.conf').first @error_action = :restart @host = 'google.com' @count_failed = 0 @count_max = 5 @state = :unsure # Any of :ok, :unsure, :failed def new_state(s) if s != @state @state = s end end def check network_dev = '' netctl_dev = '' @checks.each { |c| res = case c when /ppp/ IO.read('/proc/net/dev') =~ /^\s*#{network_dev}:/ when /default/ System.run_str('/usr/bin/route -n') =~ /^0\.0\.0\.0/ when /host/ System.run_bool("/usr/bin/host #{@host}") when /ping/ System.run_bool("/usr/bin/ping -w 10 -c 3 #{@host}") when /httping/ System.run_bool("/usr/bin/httping -t 10 -c 2 #{@host}") when /openvpn/ IO.read('/proc/net/dev') =~ /^\s*tun0:/ else dputs(1) { "Don't know about check #{c}" } true end if res dputs(3) { "Check #{c} returns true" } else dputs(2) { "Check #{c} failed" } if @count_failed += 1 >= @count_max failed(c) end break end } end def is_broken end end end end
# frozen_string_literal: true module Types # gql type for Payee model class PagedTransactionsType < Types::BaseObject field :page, Integer, null: false field :page_total, Integer, null: false field :transactions, [TransactionType], null: false end end
class CreateTableCourseSubjects < ActiveRecord::Migration def self.up create_table :course_subjects do |t| t.string :name t.integer :parent_id t.string :parent_type t.string :code t.boolean :no_exams, :default => false t.integer :max_weekly_classes t.boolean :is_deleted, :default => false t.decimal :credit_hours ,:precision => 15, :scale => 2 t.boolean :prefer_consecutive, :default => false t.decimal :amount ,:precision => 15, :scale => 2 t.boolean :is_asl, :default => false t.integer :asl_mark t.boolean :is_sixth_subject t.integer :subject_skill_set_id t.timestamps end end def self.down drop_table :course_subjects end end
class CreateTaxons < ActiveRecord::Migration def change create_table :taxons do |t| t.integer "parent_id" t.integer "lft" t.integer "rgt" t.integer "children_count", default: 0 t.integer "depth", default: 0 end remove_columns :items, :parent_id, :lft, :rgt, :children_count, :depth remove_columns :lists, :type rename_column :items, :sort_id, :list_id rename_column :items, :sort_name, :list_name end end
require 'spec_helper' feature 'Creating Activity' do before do sign_in_as!(FactoryGirl.create(:admin_user)) visit '/' click_link 'New Activity' end scenario "can create an activity" do fill_in 'Name', with: 'Student Project' fill_in 'Description', with: 'An activity for student project' click_button 'Create Activity' expect(page).to have_content('Activity has been created.') #### activity = Activity.where(name: 'Student Project').first expect(page.current_url).to eql(activity_url(activity)) title = "Student Project - Activities - Shooring" expect(page).to have_title(title) end scenario "can not create an activity when with blank name" do click_button 'Create Activity' expect(page).to have_content("Activity has not been created") expect(page).to have_content("Name can't be blank") end end
require 'test_helper' class CategoryTest < ActiveSupport::TestCase def setup @category = Category.new(name: 'Dom') end #Happy-path test "valid category name" do assert @category.valid? end test "invalid without name" do @category.name = nil refute @category.valid?,'saved user without a name' assert_not_nil @category.errors[:name], 'no validation error: name present' end end
module Fog module AWS class EC2 class Real require 'fog/aws/parsers/ec2/describe_volumes' # Describe all or specified volumes. # # ==== Parameters # * volume_id<~Array> - List of volumes to describe, defaults to all # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'volumeSet'<~Array>: # * 'availabilityZone'<~String> - Availability zone for volume # * 'createTime'<~Time> - Timestamp for creation # * 'size'<~Integer> - Size in GiBs for volume # * 'snapshotId'<~String> - Snapshot volume was created from, if any # * 'status'<~String> - State of volume # * 'volumeId'<~String> - Reference to volume # * 'attachmentSet'<~Array>: # * 'attachmentTime'<~Time> - Timestamp for attachment # * 'device'<~String> - How value is exposed to instance # * 'instanceId'<~String> - Reference to attached instance # * 'status'<~String> - Attachment state # * 'volumeId'<~String> - Reference to volume def describe_volumes(volume_id = []) params = AWS.indexed_param('VolumeId', volume_id) request({ 'Action' => 'DescribeVolumes', :idempotent => true, :parser => Fog::Parsers::AWS::EC2::DescribeVolumes.new }.merge!(params)) end end class Mock def describe_volumes(volume_id = []) response = Excon::Response.new volume_id = [*volume_id] if volume_id != [] volume_set = @data[:volumes].reject {|key,value| !volume_id.include?(key)}.values else volume_set = @data[:volumes].values end if volume_id.length == 0 || volume_id.length == volume_set.length volume_set.each do |volume| case volume['status'] when 'attaching' if Time.now - volume['attachmentSet'].first['attachTime'] > Fog::Mock.delay volume['attachmentSet'].first['status'] = 'in-use' volume['status'] = 'in-use' end when 'creating' if Time.now - volume['createTime'] > Fog::Mock.delay volume['status'] = 'available' end when 'deleting' if Time.now - @data[:deleted_at][volume['volumeId']] > Fog::Mock.delay @data[:deleted_at].delete(volume['volumeId']) @data[:volumes].delete(volume['volumeId']) end end end volume_set = volume_set.reject {|volume| !@data[:volumes][volume['volumeId']]} response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'volumeSet' => volume_set } response else raise Fog::AWS::EC2::NotFound.new("The volume #{volume_id.inspect} does not exist.") end end end end end end
module RPC class Subtract def initialize(params) case params when Hash @minuend = params.delete(:minuend).to_i @subtrahend = params.delete(:subtrahend).to_i when Array @minuend, @subtrahend = params.map(&:to_i) else raise end rescue raise RPCDispatcher::InvalidParams end def execute @minuend - @subtrahend end end end
# encoding: UTF-8 # -- # Copyright (C) 2008-2010 10gen Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ++ module Mongo module URIParser DEFAULT_PORT = 27017 MONGODB_URI_MATCHER = /(([-_.\w\d]+):([-_\w\d]+)@)?([-.\w\d]+)(:([\w\d]+))?(\/([-\d\w]+))?/ MONGODB_URI_SPEC = "mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/database]" extend self # Parse a MongoDB URI. This method is used by Connection.from_uri. # Returns an array of nodes and an array of db authorizations, if applicable. # # @private def parse(string) if string =~ /^mongodb:\/\// string = string[10..-1] else raise MongoArgumentError, "MongoDB URI must match this spec: #{MONGODB_URI_SPEC}" end nodes = [] auths = [] specs = string.split(',') specs.each do |spec| matches = MONGODB_URI_MATCHER.match(spec) if !matches raise MongoArgumentError, "MongoDB URI must match this spec: #{MONGODB_URI_SPEC}" end uname = matches[2] pwd = matches[3] host = matches[4] port = matches[6] || DEFAULT_PORT if !(port.to_s =~ /^\d+$/) raise MongoArgumentError, "Invalid port #{port}; port must be specified as digits." end port = port.to_i db = matches[8] if uname && pwd && db auths << {'db_name' => db, 'username' => uname, 'password' => pwd} elsif uname || pwd || db raise MongoArgumentError, "MongoDB URI must include all three of username, password, " + "and db if any one of these is specified." end nodes << [host, port] end [nodes, auths] end end end
require 'test_helper' class TrkDatatablesTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::TrkDatatables::VERSION end end
class VotesController < ApplicationController def create vote = Vote.new(race_id: params[:race_id], voter_id: params[:voter_id], candidate_id: params[:candidate_id]) vote.save ? (render json: vote) : (render json: vote.errors) end def index render json: Candidate.all end def destroy Vote.delete(params[:id]) render json: "Vote no longer exists! Dont worry it didnt count anyway." end end
class Ticket attr_reader :id attr_accessor :customer_id, :film_id def initialize(info) @id = info['id'].to_i if info['id'] @customer_id = info['customer_id'].to_i @film_id = info['film_id'].to_i @screening_id = info['screening_id'].to_i end def save sql = "INSERT INTO tickets (customer_id, film_id, screening_id) VALUES ($1, $2, $3) RETURNING *" values = [@customer_id, @film_id, @screening_id] result = SqlRunner.run(sql, values) @id = result.first['id'].to_i end def update() sql = "UPDATE tickets SET customer_id = $1, film_id = $2, screening_id = $4 WHERE id = $3 " values = [@customer_id, @film_id, @id, @screening_id] SqlRunner.run(sql, values) end def delete() sql = "DELETE FROM tickets WHERE id = $1" values = [@id] SqlRunner.run(sql, values) end def self.map_items(ticket_data) ticket_data.map { |ticket| Ticket.new(ticket) } end def self.all sql = "SELECT * FROM tickets" result = SqlRunner.run(sql) return self.map_items(result) end def self.delete_all sql = "DELETE FROM tickets" SqlRunner.run(sql) end def self.find_by_id(id) sql = "SELECT * FROM tickets WHERE id = $1" values = [id] result = SqlRunner.run(sql, values) if result.count > 0 ticket.map_items(result) else return nil end end end
# misc utility functions that are common in my solutions module Utils # check the AOC_DEBUG env var def self.enable_debug_output? ENV.has_key?("AOC_DEBUG") ? ENV["AOC_DEBUG"] == "true" : false end # get a parameter from the command line or else default def self.cli_param_or_default(n=0, default="") ARGV.size > n ? ARGV[n] : default end # read a file to string, strip any trailing whitespace def self.get_input_file(filename) File.read(filename).strip end # write an array of pixel RGB triples to a PPM file def self.write_ppm(width, height, pixels, filename) File.open(filename, "w") do |file| file.print("P3\n%i %i\n255\n" % [width, height]) pixels.each do |r,g,b| file.print("%i %i %i\n" % [r,g,b].map{ |v| v }) # wrap output to 255 end end end end
class RemoveSelectedPolygonClassColourIdFromLayers < ActiveRecord::Migration def up remove_column :layers, :selected_polygon_class_colour_id end def down add_column :layers, :selected_polygon_class_colour_id, :integer end end
# Copyright 2014 Square Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Helper methods for email content. module MailHelper include TextBacktraceRendering # The typical maximum line width for plaintext emails (per RFC 2822). EMAIL_WRAP_WIDTH = 78 # Quotes a text block for email use. Adds chevron(s) and a space before each # line. Rewraps the content only as necessary to keep total width at 78 # characters: Other line breaks are preserved. # # @param [String] text The text to quote. # @param [Fixnum] level The quote level. # @return [String] The quoted text. def email_quote(text, level=1) width = EMAIL_WRAP_WIDTH - level - 1 lines = word_wrap(text, line_width: width).split("\n") lines.map!(&:lstrip) lines.map! { |line| '>'*level + ' ' + line } lines.join("\n") end # Rewraps content for email use. Double line breaks are considered to be new # paragraphs. Single line breaks are considered to be wraps and are replaced # with spaces. New line breaks are added as necessary. # # @param [String] text The text to rewrap. # @param [Fixnum] width The new width to wrap to. # @return [String] The rewrapped text. def email_rewrap(text, width=EMAIL_WRAP_WIDTH) paragraphs = text.split("\n\n") paragraphs.each { |para| para.gsub("\n", ' ') } paragraphs.map! { |para| email_wrap para, width } paragraphs.join("\n\n") end # Wraps content for email use. Similar to {#email_rewrap}, but existing line # breaks are preserved. New line breaks are added as necessary to keep total # line width under `width`. # # @param [String] text The text to wrap. # @param [Fixnum] width The new width to wrap to. # @return [String] The wrapped text. def email_wrap(text, width=EMAIL_WRAP_WIDTH) lines = word_wrap(text, line_width: width).split("\n") lines.map!(&:lstrip) lines.join("\n") end end
#!/usr/bin/env ruby load File.expand_path(File.join(File.dirname(__FILE__), "..", "lib", "vanagon.rb")) optparse = Vanagon::OptParse.new( "#{File.basename(__FILE__)} <project-name> <platform-name> [options]", %i[workdir configdir engine] ) options = optparse.parse! ARGV project = ARGV[0] platforms = ARGV[1] targets = ARGV[2] if project.nil? or platforms.nil? warn "project and platform are both required arguments." $stderr.puts optparse exit 1 end platform_list = platforms.split(',') target_list = [] platform_list.zip(target_list).each do |pair| platform, target = pair artifact = Vanagon::Driver.new(platform, project, options.merge({ :target => target })) artifact.render end
class AddBoughtToEventItems < ActiveRecord::Migration def change add_column :event_items, :bought, :boolean, :default => false end end
class Toastunes::DirectoryParser # p = Toastunes::DirectoryParser.new(:library => 'w2') # p.parse! def initialize(options={}) @options = { :replace_artists => true, :replace_tracks => true, :replace_genres => true, :replace_covers => true }.merge(options) end # parse a directory of artist directories, # where directory structure is like: # #{Rails.root}/public/music/#{library}/Some Artist/Some Album/01 Some Track.mp3 def parse! dir = File.join(Rails.root, 'public', 'music', @options[:library]) Dir.entries(dir).reject{|a| a.match /^\./}.each do |subdir| d = File.join(dir, subdir) next unless File.directory? d parse_artist d end end # parse a hierarchy structured like this: # /path/to/Artist/Album/01.mp3 def parse_artist(artist_dir) artist_name = File.basename(artist_dir) albums = Dir.entries(artist_dir).reject{|a| a.match /^\./} albums.each do |album_title| if File.directory?(File.join(artist_dir, album_title)) parse_album(File.join(artist_dir, album_title), artist_name, album_title) end end end def parse_album(album_dir, artist_name, album_title) puts [Time.now, artist_name, album_title].join("\t") album = find_album(artist_name, album_title) album.library = @options[:library] # parse tracks Dir.entries(album_dir).reject{|a| a.match /^\./}.grep(/\.(mp3|m4a)$/).each do |file| location = File.join(artist_name, album_title, file) track = album.tracks.detect{|t| t.location == location} next if track and !@options[:replace_tracks] filename = parse_filename(file) begin parser = Toastunes::TagParser.new(File.join(album_dir, file)) values = { :title => parser.title || filename[:track_title], :location => location, :created_at => Time.now, :track => parser.track_number || filename[:track_number], :genre => parser.genre, :artist_name => parser.artist || artist_name, :kind => filename[:kind], :year => parser.year, # :size => file_size, # :duration => duration, # :bit_rate => bit_rate, # :sample_rate => sample_rate, # :itunes_pid => pid } rescue => e puts "WARNING: #{e.inspect}" values = { :title => filename[:track_title], :location => location, :created_at => Time.now, :track => filename[:track_number], :artist_name => artist_name, :kind => filename[:kind], } end add_track(album, values) end ## SAVE return if album.artist and !@options[:replace_artists] album.set_artist(artist_name) album.extract_cover(@options[:replace_covers]) # don't process if we already have a cover album.set_genre # album.genre = nil album.save rescue SignalException => e raise e rescue Exception => e puts "WARNING: #{e.inspect}" end private # find or initialize an album with the given info def find_album(artist_name, album_title) compilation = (album_title == 'Compilation') # is this a compilation? if compilation h = {:title => album_title, :compilation => true} else h = {:title => album_title, :artist_name => artist_name} end # find or initialize album album = Album.where(h).first || Album.new(h) album.compilation = compilation album end # what info can we glean from the filename? def parse_filename(file) filename = {} if file.match(/^(\d{1,2}\s+)?(.*)\.(mp3|m4a)$/i) filename[:track_number] = $1.strip if $1 filename[:track_title] = $2 filename[:kind] = $3 end filename end # update the track with the same location, or add a new one def add_track(album, values) if track = album.tracks.detect{|t| t.location == values[:location]} track.update_attributes(values) else album.tracks.create!(values) end end end
Dir["./pieces/*.rb"].each {|file| require file } require 'colorize' class MissingPieceError < RuntimeError end class InvalidMoveError < RuntimeError end class WrongColorError < RuntimeError end class Board attr_reader :grid def initialize(grid = nil) @grid = grid.nil? ? generate_grid : grid @captured_blacks = [] @captured_whites = [] end def [](pos) x, y = pos @grid[x][y] end def []=(pos, object) x, y = pos @grid[x][y] = object end def move_piece(start, target, turn) # gets valid coords from game raise MissingPieceError if self[start].nil? raise InvalidMoveError unless self[start].valid_move?(target, self) raise WrongColorError if self[start].color != turn capture_piece(target) unless self[target].nil? self[start].move(target) end def in_check?(color) pieces = grid.flatten.compact king = pieces.find { |piece| piece.color == color && piece.is_a?(King) } king_pos = king.position enemy_pieces = pieces.select { |piece| piece.color != color } enemy_pieces.any? { |piece| piece.valid_move?(king_pos, self) } end def checkmate?(color) in_check?(color) && no_legal_moves?(color) end def stalemate? [:white, :black].any? { |color| !in_check?(color) && no_legal_moves?(color)} end def no_legal_moves?(color) pieces = grid.flatten.compact our_pieces = pieces.select { |piece| piece.color == color } our_pieces.none? { |piece| piece.valid_moves.count > 0 } end def dup new_grid = @grid.map do |row| row.map do |piece| piece.nil? ? nil : piece.dup end end Board.new(new_grid) end def display puts " A B C D E F G H" @grid.each_with_index do |row, x| print "#{8 - x} " row.each_with_index do |piece, y| if piece.nil? print color_square(x, y, " ") else print color_square(x, y, " #{piece.render} ") end end if x == 0 print " " + @captured_whites.map { |piece| piece.render }.join(" ") elsif x == 7 print " " + @captured_blacks.map { |piece| piece.render }.join(" ") end puts "" end end def blank_grid_test @grid = Array.new(8) { Array.new(8) { nil } } end private def capture_piece(target) @captured_blacks << self[target] if self[target].color == :black @captured_whites << self[target] if self[target].color == :white end def color_square(row, col, string) if (row.even? && col.odd?) || (row.odd? && col.even?) string.colorize(:background => :cyan) else string.colorize(:background => :light_cyan) end end def generate_grid piece_pos = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook] grid = Array.new(8) { Array.new(8) { nil } } 0.upto(7) do |y| grid[0][y] = piece_pos[y].new([0, y], :black, self) end 0.upto(7) do |y| grid[1][y] = Pawn.new([1, y], :black, self) end 0.upto(7) do |y| grid[6][y] = Pawn.new([6, y], :white, self) end 0.upto(7) do |y| grid[7][y] = piece_pos[y].new([7, y], :white, self) end grid end end
namespace :db do desc "TODO" task rearrange: :environment do if Rails.env == "development" then ENV['VERSION']= '0' Rake::Task['db:migrate'].invoke Rake::Task['db:migrate'].reenable ENV.delete 'VERSION' Rake::Task["db:migrate"].invoke Rake::Task['db:seed'].execute() puts "done!\n" else puts "NOT PERMITED IN PRODUCTION MODE" end end desc "Adding needed partnership_depth values" task create_part_depth: :environment do percents = [15, 10, 5, 3, 2, 1, 1, 1, 1, 1] ActiveRecord::Base.connection.execute("TRUNCATE partnership_depths") # PartnershipDepth.delete_all # ActiveRecord::Base.connection.reset_sequence!('partnership_depths', 'id') percents.each do |percent| depth = PartnershipDepth.create!(percent: percent) end end desc "Adding wallets for already created users" task create_wallets: :environment do User.all.each do |user| if user.wallet.nil? Wallet.create(user: user, main_balance: 0, bonus_balance: 0) end end end # desc "Adding bonuses for first 500" # task add_bonuses: :environment do # # It may work in absolutely different way, have to save average value # # And track, which users we have already payed # average = 500 # per_person = 200 # User.all.each do |user| # user.wallet.bonus_balance += per_person # average -= 1 # end # end desc "Fixing Roles table" task fix_roles: :environment do roles = Role.all roles_data = { "user" => { description: "Новичок", switch_price: 0, month_price: 0, spam_per_week: 0, adv_per_month: 0, online_event_per_week: 0, landing_pages_number: 0, month_team_bonus_ppm: 0, partnership_depth: 1, can_edit_video: false, can_start_auction: false, know_partners_backref: false, have_investment_belay: false }, "partner" => { description: "Партнер", switch_price: 5, month_price: 5, spam_per_week: 0, adv_per_month: 0, online_event_per_week: 0, landing_pages_number: 1, month_team_bonus_ppm: 5, partnership_depth: 2, can_edit_video: false, can_start_auction: false, know_partners_backref: true, have_investment_belay: false }, "vip" => { description: "VIP Партнер", switch_price: 15, month_price: 30, spam_per_week: 1, adv_per_month: 1, online_event_per_week: 1, landing_pages_number: 3, month_team_bonus_ppm: 50, partnership_depth: 5, can_edit_video: true, can_start_auction: true, know_partners_backref: true, have_investment_belay: false }, "leader" => { description: "Лидер", switch_price: 30, month_price: 50, spam_per_week: 10, adv_per_month: 5, online_event_per_week: 3, landing_pages_number: 8, month_team_bonus_ppm: 70 , partnership_depth: 10, can_edit_video: true, can_start_auction: true, know_partners_backref: true, have_investment_belay: true } } roles.each do |role| name = role.name if not roles_data.keys.size role.destroy! elsif (roles_data.keys.include? name) role.update_attributes!(**roles_data[name]) roles_data.delete(name) else name = roles_data.keys.first role.update_attributes!(name: name, **roles_data[name]) roles_data.delete(name) end end User.all.each do |user| user.update_attributes!(role: Role.find_by(name: 'user')) end end end # Role.create name: "leader", description: "Лидер" # Role.create name: "user", description: "Новичок" # Role.create name: "vip", description: "VIP Партнер" # Role.create name: "partner", description: "Партнер"
require 'httparty' require 'base64' require 'openssl' module ZanoxPublisher # Represents a Zanox Product API error. Contains specific data about the error. class ZanoxError < StandardError attr_reader :data def initialize(data) @data = data # should contain Code, Message, and Reason code = data['code'].to_s message = data['message'].to_s reason = data['reason'].to_s super "The Zanox Product API responded with the following error message: #{message} Error reason: #{reason} [code: #{code}]" end end # Raised for HTTP response codes of 400...500 class ClientError < StandardError; end # Raised for HTTP response codes of 500...600 class ServerError < StandardError; end # Raised for HTTP response code of 400 class BadRequest < ZanoxError; end # Raised when authentication information is missing class AuthenticationError < StandardError; end # Raised when authentication fails with HTTP response code of 403 class Unauthorized < ZanoxError; end # Raised for HTTP response code of 404 class NotFound < ClientError; end # Raw connection to the Zanox API # # @attr [String] relative_path The default relative path used for a request class Connection include HTTParty API_URI = 'https://api.zanox.com' DATA_FORMAT = 'json' API_VERSION = '2011-03-01' base_uri "#{API_URI}/#{DATA_FORMAT}/#{API_VERSION}" USER_AGENT_STRING = "ZanoxPublisher/#{VERSION} (ruby #{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}; #{RUBY_PLATFORM})" attr_accessor :relative_path # Initializes a new connection instance of ZanoxPublisher. # It requires authentication information to access the Publisher API. # The relative path is used as the default for HTTP method calls. # # The connect ID and secret key can be passed as parameters, # else the ZanoxPublisher::authenticate information is taken. # # @param relative_path [String] The default relative path of the resource # @param connect_id [String] The connect ID of your account for authentication # @param secret_key [String] The secret key of your account for authentication # # @example # connection = ZanoxPublisher::Connection.new("/profiles", "<your_client_id>", "<your_client_secret>") #=> #<Connection ...> # connection.get #=> #<HTTParty::Response ...> # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.get('/profiles') #=> #<Hash::Response ...> # def initialize(relative_path = '', connect_id = ZanoxPublisher.connect_id, secret_key = ZanoxPublisher.secret_key) @connect_id, @secret_key = connect_id, secret_key @relative_path = relative_path @connection = self.class end # Sends a GET request for a public resource - auth with connect ID # # For more information on authentication see {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest} # # @param relative_path [String] The relative path of the API resource # @param params [Hash] The HTTParty params argument # # @return [Hash] # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.get('/path') #=> #<Hash::Response ...> def get(relative_path = @relative_path, params = {}) handle_response connection.get(relative_path, public_auth(params)) end # Sends a POST request for a public resource - auth with connect ID # # For more information on authentication see {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest} # # @param relative_path [String] The relative path of the API resource # @param params [Hash] The HTTParty params argument # # @return [Hash] # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.post('/path') #=> #<Hash::Response ...> def post(relative_path = @relative_path, params = {}) handle_response connection.post(relative_path, public_auth(params)) end # Sends a PUT request for a public resource - auth with connect ID # # For more information on authentication see {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest} # # @param relative_path [String] The relative path of the API resource # @param params [Hash] The HTTParty params argument # # @return [Hash] # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.put('/path') #=> #<Hash::Response ...> def put(relative_path = @relative_path, params = {}) handle_response connection.put(relative_path, public_auth(params)) end # Sends a DELETE request for a public resource - auth with connect ID # # For more information on authentication see {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest} # # @param relative_path [String] The relative path of the API resource # @param params [Hash] The HTTParty params argument # # @return [Hash] # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.delete('/path') #=> #<Hash::Response ...> def delete(relative_path = @relative_path, params = {}) handle_response connection.delete(relative_path, public_auth(params)) end # Sends a GET request for a private resource - auth with signature # # For more information on authentication see {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest} # # @param relative_path [String] The relative path of the API resource # @param params [Hash] The HTTParty params argument # # @return [Hash] # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.signature_get('/path') #=> #<Hash::Response ...> def signature_get(relative_path = @relative_path, params = {}) handle_response connection.get(relative_path, private_auth('GET', relative_path, params)) end # Sends a POST request for a private resource - auth with signature # # For more information on authentication see {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest} # # @param relative_path [String] The relative path of the API resource # @param params [Hash] The HTTParty params argument # # @return [Hash] # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.signature_post('/path') #=> #<Hash::Response ...> def signature_post(relative_path = @relative_path, params = {}) handle_response connection.post(relative_path, private_auth('POST', relative_path, params)) end # Sends a PUT request for a private resource - auth with signature # # For more information on authentication see {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest} # # @param relative_path [String] The relative path of the API resource # @param params [Hash] The HTTParty params argument # # @return [Hash] # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.signature_put('/path') #=> #<Hash::Response ...> def signature_put(relative_path = @relative_path, params = {}) handle_response connection.put(relative_path, private_auth('PUT', relative_path, params)) end # Sends a DELETE request for a private resource - auth with signature # # For more information on authentication see {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest} # # @param relative_path [String] The relative path of the API resource # @param params [Hash] The HTTParty params argument # # @return [Hash] # # @example # connection = ZanoxPublisher::Connection.new #=> #<Connection ...> # connection.signature_delete('/path') #=> #<Hash::Response ...> def signature_delete(relative_path = @relative_path, params = {}) handle_response connection.delete(relative_path, private_auth('DELETE', relative_path, params)) end private attr_reader :connection # Internal routine to handle the HTTParty::Response def handle_response(response) # :nodoc: case response.code when 400 #IN CASE WE WANT MORE PRECISE ERROR NAMES #data = response.parsed_response #case data['code'] #when 230 # raise ParameterDataInvalid.new data #else # raise BadRequest.new data #end raise BadRequest.new(response.parsed_response) when 403 raise Unauthorized.new(response.parsed_response) when 404 raise NotFound.new when 400...500 raise ClientError.new when 500...600 raise ServerError.new else response.parsed_response end end # Authentication header for public resources of the Zanox API # Public resources - auth with connection ID. # # For details access the guide found {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest here}. def public_auth(params) raise AuthenticationError, 'Please provide your connect ID.' if @connect_id.nil? auth = { 'Authorization' => "ZXWS #{@connect_id}" } if params.has_key? :headers params[:headers].merge(auth) else params[:headers] = auth end params end # Authentication header for private resources of the Zanox API # Private resources - auth with signature. # # For details access the guide found {https://developer.zanox.com/web/guest/authentication/zanox-oauth/oauth-rest here}. # Signature = Base64( HMAC-SHA1( UTF-8-Encoding-Of( StringToSign ) ) ); # StringToSign = HTTP-Verb + URI + timestamp + nonce # HTTP Verb - GET, POST, PUT or DELETE; # URI - exclude return format and API version date, include path parameters http://api.zanox.com/json/2011-03-01 -> /reports/sales/date/2013-07-20 # Timestamp - in GMT, format "EEE, dd MMM yyyy HH:mm:ss"; # Nonce - unique random string, generated at the time of request, valid once, 20 or more characters def private_auth(verb, relative_path, params) raise AuthenticationError, 'Please provide your connect ID.' if @connect_id.nil? raise AuthenticationError, 'Please provide your secret key.' if @secret_key.nil? # API Method: GET Sales for the date 2013-07-20 # 1. Generate nonce and timestamp timestamp = Time.new.gmtime.strftime('%a, %e %b %Y %T GMT').to_s # %e is with 0 padding so 06 for day 6 else use %d #timestamp = Time.new.gmtime.strftime('%a, %d %b %Y %T GMT').to_s nonce = OpenSSL::Digest::MD5.hexdigest((Time.new.usec + rand()).to_s) # 2. Concatinate HTTP Verb, URI, timestamp and nonce to create StringToSign string_to_sign = "#{verb}#{relative_path}#{timestamp}#{nonce}" # 3. Hash the StringToSign using the secret key as HMAC parameter signature = Base64.encode64("#{OpenSSL::HMAC.digest('sha1', @secret_key, string_to_sign)}").chomp # 4. Add information to request headers auth = { 'Authorization' => "ZXWS #{@connect_id}:#{signature}", 'Date' => timestamp, 'nonce' => nonce } if params.has_key? :headers params[:headers].merge(auth) else params[:headers] = auth end params end end end
class Api::GoalSessionsController < ApiController before_action :authenticate! before_action :find_goal_session, only: [ :show, :update, :destroy, :invite, :invite_by_email, :suggest_buddies] before_action :validate_friend_id!, only: [ :invite ] def index success(data: current_user.goal_sessions) end def show success(data: @goal_session) end def create goal_session = GoalSession.create(goal_session_params) if goal_session.valid? success(data: goal_session) else error(message: goal_session.errors.full_messages.to_sentence) end end def update if @goal_session.update(goal_session_params) success(data: @goal_session) else error(message: @goal_session.errors.full_messages.to_sentence) end end def handle_start_end goal = Goal.find(start_end_params[:goal_id]) service = GoalServices::StartEndGoalHandler.new(current_user, goal, start_end_params) if service.handle_success? success(data: service.goal_session) else error(message: service.error_message) end end def destroy if @goal_session.destroy success(data: { message: "Deleted successfuly!" }) else error(message: @goal_session.errors.full_messages.to_sentence) end end def invite_by_email GoalBuddiesInvitationMailer.challenge_email(current_user, @goal_session, params[:email]).deliver_now success(data: {message: "Email invitation sent!"}) end def invite goal_session = @goal_session.invite_participant_for(@friend) if goal_session.valid? PushServices::GoalNotifier.new(current_user, goal_session.goal).notify_challenge_to(@friend) success(data: { message: "Invitation sent to #{@friend.display_name}" }) else error(message: goal_session.errors.full_messages.to_sentence) end end def pending_accept goal_sessions = GoalSession.pending_accept_to_join_goal_for(current_user) success(data: goal_sessions, serializer: Api::GoalSessionInvitationSerializer) end def accept current_pending_goal_sessions = GoalSession.pending_accept_to_join_goal_for(current_user) goal_session = current_pending_goal_sessions.find_by_id(params[:id]) return error(message: "You does not have any request to join this goal.") if goal_session.blank? goal_session.is_accepted = true if goal_session.save PushServices::GoalNotifier.new(current_user, goal_session.goal).notify_challenge_accepted_to(goal_session.creator) success(data: "Accepted to join goal: #{goal_session.goal_detail_name}") else error(message: "Fail to join goal: #{goal_session.goal_detail_name}") end end def suggest_buddies joined_participant_ids = @goal_session.goal.goal_sessions.pluck(:participant_id) rescue [] joined_participant_ids = joined_participant_ids + [current_user.id] success(data: User.where.not(id: joined_participant_ids)) end private def start_end_params params.permit(:status, :goal_id, :remind_user_at, :score) end def find_goal_session @goal_session ||= GoalSession.find(params[:id]) end def goal_session_params @goal_session_params ||= params.require(:goal_session).permit(*Settings.params_permitted.goal_session) end end
class Api::V1::LibraryController < Api::V1::UserApiController before_action :set_library before_action :set_book, only: [:add_book, :remove_book] def show render json: current_v1_user.library.books end def add_book is_added = @library.add_book @book render json: { book_id: @book.slug, added: is_added }, status: :ok end def remove_book is_removed = @library.remove_book @book render json: { book_id: @book.slug, removed: is_removed }, status: :ok end private def set_library @library = current_v1_user.library end def set_book @book = Book.friendly.find(params[:id]) end end
# encoding: UTF-8 module CDI module V1 module LearningTracks class AddAuthorService < BaseUpdateService record_type ::LearningTrack attr_reader :added_moderators def changed_attributes return [] if fail? [:moderators] end private def record_params @_params ||= { moderator_ids: @options.delete(:users_ids) || @options.delete(:moderator_ids) } end def update_record @users = User.where(id: record_params[:moderator_ids]) @added_moderators = [] @users.each do |user| if user_eligible_for_moderation?(user) if user.add_as_track_moderator @record @added_moderators << user end end end end def update_errors @users.map do |user| { user.id => process_error_message_for_key('users.not_eligible_for_moderation', {}) } end end def user_eligible_for_moderation?(user) return false if user.blank? || user.id == @user.id user.backoffice_profile? && !(user.moderator_of_track? @record) end def success_updated? @added_moderators.any? end def after_success notify_users end def notify_users @added_moderators.each do |moderator| create_system_notification_async( sender_user: @user, receiver_user: moderator, notification_type: :added_as_track_author, notificable: @record ) end end end end end end
class DropApproverComments < ActiveRecord::Migration def change drop_table :approver_comments end end
# nome.rb class Nome # Define métodos getter padrão mas não métodos setter attr_reader :primeiro, :ultimo # Quando alguém tenta escrever um primeiro nome, force regras sobre ele. def primeiro=(primeiro) if primeiro == nil || primeiro[0].size == 0 raise ArgumentError.new('Todos precisam ter um primeiro nome!') end primeiro = primeiro.dup primeiro[0] = primeiro[0].chr.capitalize @primeiro = primeiro # Duplica o objet # chr => Retorna string correpondente ao código # Capitalize => Transforma string em caixa alta end # Quando alguém tenta escrever um último nome, force regras sobre ele. def ultimo=(ultimo) if ultimo == nil || ultimo.size == 0 raise ArgumentError.new('Todos devem ter um último nome.') end @ultimo = ultimo end def nome_completo "#{primeiro} #{ultimo}" end # Delega para o método setter ao invés de escrever na instância diretamente. def initialize(primeiro, ultimo) self.primeiro = primeiro self.ultimo = ultimo end end jacob = Nome.new('Jacob', 'Berendes') jacob.primeiro = 'Mary Sue' puts jacob.nome_completo john = Nome.new('john', 'von neumann') puts john.nome_completo john.primeiro = 'john' puts john.primeiro john.primeiro = nil
class Agregarimagendepartamento < ActiveRecord::Migration def change change_table :departamentos do |x| x.string :urlimg end end end
Rails.application.routes.draw do devise_for :users root to: 'pages#home' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html resources :recipes, except: [ :new, :create ] do resources :orders, only: [ :new, :create ] resources :amounts, only: [ :new, :create ] end resources :orders, only: [ :destroy ] do member do patch :increment patch :decrement end end resources :amounts, only: :destroy resources :baskets, only: [ :show ] resources :supermarkets do resources :recipes, only: [ :new, :create ] resources :ingredients end resources :ordered_amounts do member do patch :increment patch :decrement end end resources :confirmation_pages, only: [ :show ] end
# Write your code here. def line(katz_deli) if katz_deli == [] puts "The line is currently empty." else the_line = "The line is currently:" for count in 0...katz_deli.size the_line += " #{count+1}. #{katz_deli[count]}" end puts the_line end end def take_a_number(katz_deli, name) katz_deli.push(name) puts "Welcome, #{name}. You are number #{katz_deli.size} in line." end def now_serving(katz_deli) next_person = katz_deli.shift if next_person == nil puts "There is nobody waiting to be served!" else puts "Currently serving #{next_person}." end end
require 'publishing_api_presenters/edition.rb' require 'publishing_api_presenters/case_study.rb' require 'publishing_api_presenters/placeholder.rb' require 'publishing_api_presenters/unpublishing.rb' module PublishingApiPresenters def self.presenter_for(model, options={}) presenter_class_for(model).new(model, options) end def self.publish_intent_for(model) PublishingApiPresenters::PublishIntent.new(model) end def self.coming_soon_for(model) PublishingApiPresenters::ComingSoon.new(model) end def self.presenter_class_for(model) if model.is_a?(::Edition) presenter_class_for_edition(model) elsif model.is_a?(::Unpublishing) PublishingApiPresenters::Unpublishing else PublishingApiPresenters::Placeholder end end def self.presenter_class_for_edition(edition) if edition.is_a?(::CaseStudy) PublishingApiPresenters::CaseStudy else PublishingApiPresenters::Edition end end end
require "google/api_client" require "google_drive" require 'openssl' OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE class Water def initialize # Creates a session. This will prompt the credential via command line for the # first time and save it to config.json file for later usages. session = GoogleDrive.saved_session("config.json") # First worksheet of # https://docs.google.com/spreadsheet/ccc?key=pz7XtlQC-PYx-jrVMJErTcg # Or https://docs.google.com/a/someone.com/spreadsheets/d/pz7XtlQC-PYx-jrVMJErTcg/edit?usp=drive_web @ws = session.spreadsheet_by_key("1xlOorpivOmFpEcWvCKn_rF9yRMGUNEB9JaIE4-ZUtAU").worksheets[0] end def new_entry() p 'Did you water them right now? (y/n)' ans = gets.chomp if ans === "" || ans === "y" date = Time.now.strftime("%B %d, %Y") date2 = Time.now.hour else p 'What date did you water them?' date = gets.chomp p 'What hour did you them in military' date2 = gets.chomp end p 'Which box did you water? (1=veg 2=flower)' box = 'n/a' ans = gets.chomp if ans === "1" box = 'veg' elsif ans === "2" box = 'flower' end box2= box.upcase p "How long are the #{box2} lights on for?" lights = gets.chomp p 'Amount of water used by 1/2 gallon?' water = gets.chomp p 'Did you use any nutes? y/n' ans = gets.chomp nutes = 'none' if ans === 'y' p 'What nutes did you use (as array)?' p '1: Big Bloom, 2: Grow Big, 3: Tiger Bloom, 4: Other' ans_nutes = gets.chomp nutes = [] ans_nutes.split('').each do |x| if x === '1' y = 'Big Bloom' elsif x === '2' y = 'Grow Big' elsif x === '3' y = 'Tiger Bloom' elsif x === '4' p 'What was the other nutes that you used?' y = gets.chomp p y end p "What percentage of #{y} did you use? (.5)" ans_perc = gets.chomp.to_f * 100 nutes << [y, "#{ans_perc}%"] end end p 'Did you use calmag? y/n' calmag = 'TRUE' ans = gets.chomp if ans === "n" calmag = 'FALSE' end p 'Did you use any extra nutrients? y/n' ans = gets.chomp extras = 'none' if ans === 'y' p 'What extras did you use?' p '1: Molasses, 2: Milk, 3: Other' ans_nutes = gets.chomp extras = [] ans_nutes.split('').each do |x| if x === '1' y = 'Molasses' p 'How much molasses did you use tbs/ga?' ans_perc = gets.chomp ans_perc += ' tbs/ga' elsif x === '2' y = 'Milk' p 'How much milk did you use ounces/ga?' ans_perc = gets.chomp ans_perc += ' oz/ga' elsif x === '3' p 'What were the other extras that you used?' y = gets.chomp p "How much #{y} did you use with the unit user per gallon?" ans_perc = gets.chomp ans_perc += "/ga" end extras << [y, ans_perc] end end p 'Any other issues?' issues = gets.chomp next_row = @ws.num_rows + 1 ak = [date, date2, box, water, nutes, lights, extras, calmag, issues] ak.each_with_index do |word, i| @ws[next_row, i+1] = word end @ws.save #==> [["fuga", ""], ["foo", "bar]] # Reloads the worksheet to get changes by other clients. @ws.reload end def last_two() last_two = @ws.rows.last(2) p last_two.first p last_two.last end end water = Water.new p 'Is this a new entry? (y/n)' ans = gets.chomp if ans === 'n' p 'See last two waterings? y/n' ans = gets.chomp if ans === "y" || ans === "" water.last_two() end else water.new_entry() end
# == Schema Information # # Table name: plays # # id :bigint(8) not null, primary key # x :integer # y :integer # game_id :bigint(8) # created_at :datetime not null # updated_at :datetime not null # FactoryBot.define do factory :play do x { nil } y { nil } game { nil } end end
class ApplicationController < ActionController::API def set_channel @channel = params.require(:channel) @channel = "##{@channel}" unless @channel.start_with?('@') end def set_actor @actor = actor_params end def set_repository @repository = repository_params end def actor_params params.require(:actor).permit(:username, :display_name, links: { html: :href, avatar: :href }) end def repository_params params.require(:repository).permit(:full_name, links: {html: :href}) end def comment_params params.require(:comment).permit(:id, :created_on, :updated_on, parent: %i(id), content: %i(raw html markup), inline: %i(path from to), links: {self: :href, html: :href} ) end def log_and_respond_web_client_error(ex) Rails.logger.error "response: #{ex.response.to_hash}" if ex.response Rails.logger.error "message: #{ex.message}" Rails.logger.error "backtrace: #{ex.backtrace.join("\n ")}" head :internal_server_error end end
Page Title: CXP Check My Work Example # Objects Definitions ============================================== title css .title title-bar css .title-bar show-scores_button css .assignment-button.show-scores review_button css .assignment-button.review-button completed_button css .assignment-button.review-completed-button completed-final-grading_button css .assignment-button.review-completed-final-grading-button show-api-info_button css .assignment-button.show-input-and-output new-test_button css .assignment-button.exit-button cxp-work-subit css .submit-some-cxp-work activity-content-frame css iframe#easyXDM_activityService_target_provider ============================================== @ all -------------------------------- title: near: title-bar 0px top text is: Activity Service Test Page width: 1000 to 1400px height: 10 to 20px title-bar: near: title 0px bottom width: 1000 to 1400px height: 80 to 100px show-scores_button: text is: Show Scores width: 105 to 125px height: 20 to 35px review_button: text is: Review width: 50 to 100px height: 10 to 35px completed_button: text is: Completed width: 50 to 110px height: 10 to 35px completed-final-grading_button: text is: Completed (Final Grading) width: 200 to 250px height: 10 to 35px show-api-info_button: text is: Show API Info width: 100 to 130px height: 10 to 35px new-test_button: text is: New Test width: 75 to 100px height: 10 to 35px @ all ------------------------------ activity-content-frame: component frame: cxpworkframe.spec
class Order < ApplicationRecord belongs_to :user has_many :orders_items, dependent: :destroy validates :sub_post_code, presence: true validates :sub_address, presence: true end
module Pod module Lazy class Logger def self.info(value) UI.puts "#### #{value}".ansi.blue end def self.important(value) UI.puts "#### #{value}".ansi.magenta end end end end
require 'test_helper' class GameOfLifeTest < MiniTest::Unit::TestCase def setup @game = GameOfLife.new(2,2) end def test_add_interact_rule @game.add_rule(Loneliness.new) assert_equal 1, @game.interact_rules.count end def test_add_cell cell = Cell.new('X') @game.add_cell(0, 0, cell) assert_equal cell, @game.cells[0][0] end def test_game_is_valid cell = Cell.new('X') @game.add_cell(0, 0, cell) @game.add_cell(0, 1, cell) @game.add_cell(1, 0, cell) @game.add_cell(1, 1, cell) assert @game.valid? end def test_validate_cells assert !@game.valid? end def test_set_neighbours_count add_cells setup_rules_and_play assert_equal 3, @game.cells[0][0].alive_neighbours_count assert_equal 0, @game.cells[0][0].dead_neighbours_count end def test_apply_rules end def test_play add_cells setup_rules_and_play assert @game.cells[0][0].alive? end def test_play_with_invalid_game cell = Cell.new('X') @game.add_cell(0, 0, cell) assert_raises(RuntimeError) do @game.play end assert !@game.errors.empty? end def test_block_pattern @game = GameOfLife.new(2, 2) @game.cells = [ [ Cell.new('X'), Cell.new('X') ], [ Cell.new('X'), Cell.new('X') ] ] setup_rules_and_play assert @game.cells.map{ |ar_cells| ar_cells.collect(&:label) } == [ [ 'X', 'X' ], [ 'X', 'X' ] ] end def test_bloat_pattern @game = GameOfLife.new(3, 3) @game.cells = [ [ Cell.new('X'), Cell.new('X'), Cell.new('-') ], [ Cell.new('X'), Cell.new('-'), Cell.new('X') ], [ Cell.new('-'), Cell.new('X'), Cell.new('-')] ] setup_rules_and_play assert @game.cells.map{ |ar_cells| ar_cells.collect(&:label) } == [ [ 'X', 'X', '-' ], [ 'X', '-', 'X' ], [ '-', 'X', '-' ] ] end def test_blinker_pattern @game = GameOfLife.new(3, 3) @game.cells = [ [ Cell.new('-'), Cell.new('X'), Cell.new('-') ], [ Cell.new('-'), Cell.new('X'), Cell.new('-') ], [ Cell.new('-'), Cell.new('X'), Cell.new('-') ] ] setup_rules_and_play assert @game.cells.map{ |ar_cells| ar_cells.collect(&:label) } == [ [ '-', '-', '-' ], [ 'X', 'X', 'X' ], [ '-', '-', '-' ] ] end def test_toad_pattern @game = GameOfLife.new(2, 4) @game.cells = [ [ Cell.new('-'), Cell.new('X'), Cell.new('X'), Cell.new('X') ], [ Cell.new('X'), Cell.new('X'), Cell.new('X'), Cell.new('-') ] ] setup_rules_and_play assert @game.cells.map{ |ar_cells| ar_cells.collect(&:label) } == [ [ 'X', '-', '-', 'X' ], [ 'X', '-', '-', 'X' ] ] end private def add_cells cell = Cell.new('X') @game.add_cell(0, 0, cell) cell = Cell.new('X') @game.add_cell(0, 1, cell) cell = Cell.new('X') @game.add_cell(1, 0, cell) cell = Cell.new('X') @game.add_cell(1, 1, cell) end def setup_rules_and_play @game.add_rule(Loneliness.new) @game.add_rule(OverCrowding.new) @game.add_rule(NextGeneration.new) @game.add_rule(Reproduction.new) @game.play end end
class Redirect < ApplicationRecord self.inheritance_column = :_type_disabled enum type: {twitter: 0, facebook: 1, instagram: 2} def self.create_by_type(params) redirect = Redirect.new(type: params[:type], controller: params[:controller], action: params[:action]) redirect.save #if params[:type] == "twitter" # Redirect.create(type: :twitter) #elsif params[:type] == "facebook" # Redirect.create(type: :facebook) #elsif params[:type] == "instagram" # Redirect.create(type: :instagram) #end end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :username, presence: true validates :fullname, presence: true validates :username, uniqueness: true validates :email, uniqueness: true has_many :opinions, dependent: :delete_all has_many :follows has_many :recieved_follows, foreign_key: :followed_id, class_name: 'Follow' has_many :followers, through: :recieved_follows, source: :follower, dependent: :delete_all has_many :given_follows, foreign_key: :follower_id, class_name: 'Follow' has_many :followings, through: :given_follows, source: :followed, dependent: :delete_all has_one_attached :main_image has_one_attached :cover_image validate :acceptable_main_image validate :acceptable_cover_image def acceptable_main_image return unless main_image.attached? errors.add(:main_image, 'is too big') unless main_image.byte_size <= 1.megabyte acceptable_types = ['image/jpeg', 'image/png'] errors.add(:main_image, 'must be a JPEG or PNG') unless acceptable_types.include?(main_image.content_type) end def acceptable_cover_image return unless cover_image.attached? errors.add(:cover_image, 'is too big') unless cover_image.byte_size <= 1.megabyte acceptable_types = ['image/jpeg', 'image/png'] errors.add(:cover_image, 'must be a JPEG or PNG') unless acceptable_types.include?(cover_image.content_type) end end
class AddPhotoLicenseToPosts < ActiveRecord::Migration def change add_column :posts, :photo_licensee_name, :string add_column :posts, :photo_licensee_link, :string add_column :posts, :photo_license_creative_commons, :boolean end end
# frozen_string_literal: true module Timestamps extend ActiveSupport::Concern included do field :created_at, GraphQL::Types::ISO8601DateTime, null: false field :updated_at, GraphQL::Types::ISO8601DateTime, null: false end end
# frozen_string_literal: true module LayersHelper def parse_layer_api_metadata(layer) params = { id: layer.ckan_id } uri = URI.parse("http://ace.rdidev.com:8080/api/3/action/package_show?id=" + layer.ckan_id) Rails.logger.info "Contacting uri" req = Net::HTTP::Get.new(uri.to_s) result = Net::HTTP.start(uri.host, uri.port ) {|http| http.request(req) } #result = Net::HTTP.get("http://ace.rdidev.com/api/3/action/package_show?id=" + layer.ckan_id) metadata = JSON.parse(result.body) Rails.logger.info "metadata = #{metadata}" # Rails.logger.info metadata["result"]['description'] metadata["result"] end end
class RemoveBooleanColumnsFromQuery < ActiveRecord::Migration def change remove_column :queries, :beer? remove_column :queries, :wine? remove_column :queries, :cocktail? end end
module CapistranoAppforce unless defined?(::CapistranoAppforce::VERSION) VERSION = "0.2.0" end end
module DoubleDice class Shifter < Struct.new(:matrix) def to_s shifted = '' column = 0 while column < vector_length do 0.upto(matrix.size - 1) do |line| shifted << matrix[line][column] end column += 1 end shifted.tr(' _', '') end private def vector_length @vector_length ||= matrix.first.length end end end
class Role < ActiveRecord::Base has_and_belongs_to_many :users has_and_belongs_to_many :tasks def self.options_for_select self.all.map{|r| [r.name, r.id]} end def self.options_for_facebook self.all.map{|r| "{id: %s, name: '%s'}" % [r.id, r.name]}.join(',') end def self.ROLES APP_CONFIG[:roles].split(',').map(&:strip) end def self.bootstrap(website=nil) Role.destroy_all self.ROLES.each do |role| r = Role.find_or_create_by_name role r.update_attribute :website_id, website.id if website end end def allow_rename? name !~ /(admin|super|manager)/i end def self.all p "**** NOTICE ****** If you really want to find all, use find :all *** NOTICE *****" p "**** NOTICE ****** If you really want to find all, use find :all *** NOTICE *****" find(:all) - [find_by_name('super')] end end # == Schema Information # # Table name: roles # # id :integer not null, primary key # name :string(255) # website_id :integer # created_at :datetime # updated_at :datetime #
require 'sentiment_analyzer' # Test controller for demoing the sentiment analysis engine class SentimentController < ApplicationController def check # Get list of tickers for autocomplete @tickers = ticker_json(Company.all) return unless params['symbol'] # Get cached symbol if possible @symbol = params['symbol'] @sentiments = SentimentAnalyzer.get_results(@symbol) @symbol_rating = @sentiments[:symbol_rating] @num_tweets = @sentiments[:num_tweets] @results = @sentiments[:results] rescue => e puts e.message render file: 'public/404.html', status: :not_found, layout: false end private def ticker_json(companies) list = companies.map(&:symbol) list.to_json end def sent_params params.require(:tweet) end end
class PrescriptionsController < ApplicationController before_filter :authenticate_user! before_filter :find_patient # GET /prescriptions # GET /prescriptions.json def index @prescriptions = @patient.prescriptions.all @reminder = @patient.reminder # @refill_reminder = RefillReminder.new respond_to do |format| format.html # index.html.erb format.json { render json: @prescriptions } end end # GET /prescriptions/1 # GET /prescriptions/1.json def show @prescription = @patient.prescriptions.find(params[:id]) @responses = @patient.sms_responses @response_array = [] @response_data = @responses.each { |response| @response_array << {"date" => response.created_at.strftime("%Y-%m-%d"), "response" => response.body} } respond_to do |format| format.html # show.html.erb format.json { render json: @response_array } end end # GET /prescriptions/new # GET /prescriptions/new.json def new @prescription = @patient.prescriptions.new respond_to do |format| format.html # new.html.erb format.json { render json: @prescription } end end # GET /prescriptions/1/edit def edit @prescription = @patient.prescriptions.find(params[:id]) end # POST /prescriptions # POST /prescriptions.json def create @prescription = @patient.prescriptions.build(params[:prescription]) respond_to do |format| if @prescription.save format.html { redirect_to patient_prescriptions_url, notice: 'Prescription was successfully created.' } format.json { render json: @prescription, status: :created, location: @prescription } else format.html { render action: "new" } format.json { render json: @prescription.errors, status: :unprocessable_entity } end end end # PUT /prescriptions/1 # PUT /prescriptions/1.json def update @prescription = @patient.prescriptions.find(params[:id]) respond_to do |format| if @prescription.update_attributes(params[:prescription]) format.html { redirect_to patient_prescriptions_url, notice: 'Prescription was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @prescription.errors, status: :unprocessable_entity } end end end # DELETE /prescriptions/1 # DELETE /prescriptions/1.json def destroy @prescription = @patient.prescriptions.find(params[:id]) @prescription.destroy respond_to do |format| format.html { redirect_to patient_prescriptions_path, alert: 'Prescription was successfully deleted.' } format.json { head :no_content } end end private def find_patient @patient = current_pharmacy.patients.find(params[:patient_id]) end end
class TwitterClone::Pages::Profile::Edit < Matestack::Ui::Page def response div class: "mb-3 p-3 rounded shadow-sm" do heading size: 4, text: "Your Profile", class: "mb-3" matestack_form form_config_helper do div class: "mb-3" do form_input key: :username, type: :text, placeholder: "Username", class: "form-control", init: current_username end div class: "mb-3" do button 'submit', type: :submit, class: "btn btn-primary", text: "Save!" end end end end private def form_config_helper { for: :profile, path: profile_update_path, method: :put, success: {emit: "submitted"}, failure: {emit: "form_failed"}, errors: {wrapper: {tag: :div, class: 'invalid-feedback'}, input: {class: 'is-invalid'}} } end end
class ImproveContactPhone < ActiveRecord::Migration def change # separate join table was not great idea...phone number cannot exist in # isolation so cleaner, easier management with Contact ID on table itself add_reference :phone_numbers, :contact, index: true add_foreign_key :phone_numbers, :contacts drop_table :contact_phone_numbers end end
module Do # the tests below do various things then wait for something to # happen -- so there's a potential for a race condition. to # minimize the risk of the race condition, increase this value (0.1 # seems to work about 90% of the time); but to make the tests run # faster, decrease it STEP_DELAY = 0.5 def self.at(index, &blk) EM.add_timer(index*STEP_DELAY) { blk.call if blk } end # Respect the real seconds while doing concurrent testing def self.sec(index, &blk) EM.add_timer(index) { blk.call if blk } end end
class Dancer attr_accessor :name, :age, :card_list def initialize(name, age) @name = name @age = age @pants = "grey" @card_list = [] end def pirouette "*twirls*" end def bow "*bows*" end def queue_dance_with(partner) @name = partner @card_list << @name end def card card_list end def begin_next_dance "Now dancing with #{@card_list.slice!(0)}." #card_list[0] should be "Mikhail Baryshnikov" end def pants(color) @pants = color "#{@name} is now wearing #{@pants} pants!" end end # dancer = Dancer.new("Misty Copeland", 33) # dancer.pants("green")
Rails.application.routes.draw do devise_for :admins, controllers: { sessions: 'admins/sessions', passwords: 'admins/passwords', registrations: 'admins/registrations' } devise_for :users, controllers: { sessions: 'users/sessions', passwords: 'users/passwords', registrations: 'users/registrations' } namespace :admin do get '' => 'admins#top' resources :genres, only: [:show] resources :orders, only: [:index, :show, :update] resources :arrivals, only: [:index, :update] resources :users, only: [:index, :show, :update, :destroy] do get :orders, on: :member end resources :items do resources :arrivals, only: [:new, :create, :edit, :update] end patch '/admins/items/:id/edit', to: 'items#update' end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'items#index' get '/search' => 'items#search', as: 'item_search' resources :items, only: [:index, :show] do resource :favorites, only: [:create, :destroy] resources :item_colors do resources :item_color_sizes do resource :carts, only: [:create] end end get :genre, on: :collection end ## exceptは ~を除く resources :orders, except: [:new] do get :complete, on: :member end resources :carts, only: [:create] resources :genres, only: [:show] resources :users, only: [:show, :edit, :update, :destroy] do resources :addresses, only: [:index, :new, :create, :destroy, :edit, :update] resources :carts, only: [:index, :new, :update, :destroy] resources :favorites, only: [:index] end end
# Fix the fastlane version so that we don't get any surprises while deploying. fastlane_version '2.5.0' # Don't generate README files. skip_docs # Set your JSON key file location. json_key_file "/path/to/your/downloaded/key.json" ##################### ### CONFIGURATION ### ##################### # Hockey configuration. HOCKEY_APP_API_KEY = ENV['FL_HOCKEY_API_TOKEN'] HOCKEY_APP_TEAMS = %w(1234) # Google Play configuration. GOOGLE_PLAT_IDENTIFIER = 'com.icapps.app' # Deployment configuration. SLACK_ROOM = '#jenkins' #################### ### PUBLIC LANES ### #################### # The beta lane deploys the appication to HockeyApp but prior to deploying there # are some other tasks executed like updating translations, incrementing the # build number... lane :beta do # Configuration of the translations importer can be found in the # `.translations` file in the root of the repository. update_translations # Build the application with the given configuration. build(configuration: 'Beta') end ######################## ### 🔑 PRIVATE LANES ### ######################## # Build application private_lane :build do |options| gradle( task: options[:task], # The task you want to execute. flavor: options[:flavor], # The flavor you want the task for. build_type: 'Release' # The build type you want the task for. ) end # Upload the build to HockeyApp and open it up for the given teams. private_lane :upload_to_hockey do hockey( api_token: HOCKEY_APP_API_KEY, teams: HOCKEY_APP_TEAMS.join(','), status: '2', # The status is available for download. release_type: '0' # We set the release type to be beta. ) end # Upload the build to Google Play. private_lane :upload_to_google_play do |options| # Upload the apk to Google Play. supply( track: options[:track], # The track you want to publish. package_name: GOOGLE_PLAY_IDENTIFIER ) end ################# ### CALLBACKS ### ################# # Post a notification to Slack every time a lane was successful. after_all do |lane| return unless if is_ci? slack( channel: SLACK_ROOM, success: true, default_payloads: [:lane, :test_result] attachment_properties: { message: "#{last_git_commit[:author]} did an excelent job.", } ) clean_build_artifacts end # When an error occurs we post a failure notification to Slack. error do |lane, exception| return unless if is_ci? slack( message: exception.message, channel: SLACK_ROOM, success: false, default_payloads: [:lane, :test_result], attachment_properties: { title: "#{last_git_commit[:author]} broke all the things.", } ) clean_build_artifacts end
class CreatePlayers < ActiveRecord::Migration[5.1] def change create_table :players do |t| t.integer :x_position t.integer :y_position t.integer :health t.integer :armor t.string :name t.timestamps end end end
class Band < ActiveRecord::Base extend FriendlyId friendly_id :handle, use: :slugged has_merit has_reputation :votes, source: :user, aggregated_by: :sum belongs_to :user has_many :albums, dependent: :destroy has_many :songs, through: :albums, dependent: :destroy has_many :events has_many :articles has_many :members, dependent: :destroy accepts_nested_attributes_for :songs, allow_destroy: true, :reject_if => lambda { |a| a[:title].blank? } has_attached_file :band_avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :band_avatar, content_type: /\Aimage\/.*\z/ has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy has_many :followers, through: :passive_relationships, source: :follower validates_presence_of :group_name, :city, :state, :handle validates_uniqueness_of :handle validates_associated :members accepts_nested_attributes_for :events, allow_destroy: true accepts_nested_attributes_for :albums, allow_destroy: true accepts_nested_attributes_for :members, allow_destroy: true, reject_if: :all_blank end
require "rails_helper" RSpec.describe GovukDesignSystem::HmctsBannerHelper, type: :helper do describe "#govukInput" do it "returns the correct HTML for success" do html = helper.hmctsBanner({ text: "The image was added", type: "success" }) expect(html).to match_html(<<~HTML) <div class="hmcts-banner hmcts-banner--success"> <div class="hmcts-banner__message"> The image was added <svg class="hmcts-banner__icon" focusable="false" height="25" role="presentation" viewBox="0 0 25 25" width="25" xmlns="http://www.w3.org/2000/svg"> <path d="M25,6.2L8.7,23.2L0,14.1l4-4.2l4.7,4.9L21,2L25,6.2z"></path> </svg> </div> </div> HTML end it "returns the correct HTML for information" do html = helper.hmctsBanner({ text: "The image did not finish uploading - you must refresh the image", type: "information" }) expect(html).to match_html(<<~HTML) <div class="hmcts-banner"> <div class="hmcts-banner__message"> The image did not finish uploading - you must refresh the image <svg class="hmcts-banner__icon" fill="currentColor" role="presentation" focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 25" height="25" width="25"> <path d="M13.7,18.5h-2.4v-2.4h2.4V18.5z M12.5,13.7c-0.7,0-1.2-0.5-1.2-1.2V7.7c0-0.7,0.5-1.2,1.2-1.2s1.2,0.5,1.2,1.2v4.8 C13.7,13.2,13.2,13.7,12.5,13.7z M12.5,0.5c-6.6,0-12,5.4-12,12s5.4,12,12,12s12-5.4,12-12S19.1,0.5,12.5,0.5z"></path> </svg> </div> </div> HTML end it "returns the correct HTML when a symbol type is passed" do html = helper.hmctsBanner({ text: "The image did not finish uploading - you must refresh the image", type: :information }) expect(html).to match_html(<<~HTML) <div class="hmcts-banner"> <div class="hmcts-banner__message"> The image did not finish uploading - you must refresh the image <svg class="hmcts-banner__icon" fill="currentColor" role="presentation" focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 25 25" height="25" width="25"> <path d="M13.7,18.5h-2.4v-2.4h2.4V18.5z M12.5,13.7c-0.7,0-1.2-0.5-1.2-1.2V7.7c0-0.7,0.5-1.2,1.2-1.2s1.2,0.5,1.2,1.2v4.8 C13.7,13.2,13.2,13.7,12.5,13.7z M12.5,0.5c-6.6,0-12,5.4-12,12s5.4,12,12,12s12-5.4,12-12S19.1,0.5,12.5,0.5z"></path> </svg> </div> </div> HTML end end end
json.array!(@discoveries) do |discovery| json.extract! discovery, json.url discovery_url(discovery, format: :json) end
class DocumentPresenter attr_reader(:annual_plan, :annual_report, :budget, :guideline, :opinion, :policy, :vision, :bylaws, :regulation, :directive) def initialize(documents) by_title = documents.by_title(I18n.locale).group_by(&:category) by_revision = documents.by_revision.group_by(&:category) @annual_plan = by_revision['annual_plan'] || [] @annual_report = by_revision['annual_report'] || [] @budget = by_revision['budget'] || [] @bylaws = by_title['bylaws'] || [] @directive = by_title['directive'] || [] @vision = by_title['vision'] || [] @regulation = by_title['regulation'] || [] @guideline = by_title['guideline'] || [] @opinion = by_title['opinion'] || [] @policy = by_title['policy'] || [] end end
class CreateExamLogs < ActiveRecord::Migration def change create_table :exam_logs do |t| t.references :class_registration, index: true t.string :doc t.timestamps end end end
class CreateRosterSpots < ActiveRecord::Migration[5.2] def change create_table :roster_spots, id: :uuid do |t| t.boolean :archived, default: false t.datetime :archived_at t.datetime :joined_at t.string :role t.references :team, foreign_key: true, null: false, type: :uuid t.references :user, foreign_key: true, null: false, type: :uuid t.timestamps end end end
class CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.string :fullname t.string :shortname t.string :symbol t.string :manager t.string :president t.string :address t.string :post_code t.string :city t.string :fax t.string :phone t.string :stadium_name t.string :stadium_directions t.string :contact_person_name t.string :contact_person_phone t.string :contact_person_email t.integer :points_to_add t.integer :points_to_remove t.integer :ranking t.string :custom_text1 t.integer :yearly_budget t.integer :total_games_win t.integer :total_games_lose t.integer :total_games_draw t.boolean :supplent t.byte :team_logo_file t.boolean :enabled t.integer :tgroup t.timestamps end end def self.down drop_table :teams end end
# def full_title(page_title) # base_title = "Sample App" # if page_title.empty? # base_title # else # "#{ base_title } | #{ page_title }" # end # end include ApplicationHelper #include UserPageSpecUtility def valid_signin(user) visit signin_path fill_in "Email", with: user.email fill_in "Password", with: user.password click_button "Sign in" end RSpec::Matchers.define :have_error_message do |message| match do |page| page.should have_selector('div.alert.alert-error', text: message) end end def valid_input fill_in "Name" , with: "Example User" fill_in "Email", with: "user@example.com" fill_in "Password", with: "foobar" fill_in "Confirmation", with: "foobar" end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'deploy_rails_as_rpm/version' Gem::Specification.new do |gem| gem.name = "deploy_rails_as_rpm" gem.version = DeployRailsAsRPM::VERSION gem.authors = ["Tilo Sloboda\n"] gem.email = ["tilo.sloboda@gmail.com\n"] gem.description = %q{Helps you to deploy your Rails app as an RPM. This Gem helps you generate an RPM.spec file from a given Rails application, build the RPM, and quickly deploy it to production servers -- without having to install RVM, install gems or bundles on your production servers.} gem.summary = %q{Helps you to deploy your Rails app as an RPM in seconds. This Gem helps you generate an RPM.spec file, helps you build the RPM, and to automate the deployment via RPM} gem.homepage = "https://github.com/tilo/deploy_rails_as_rpm" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] end
module Higan module Base module ClassMethods class Fail < StandardError end def development? Rails.env == "development" end def ftp_data ftp_store.each_pair.map do |k, v| {name: k}.merge!(v.to_h) end end def local_data local_store.each_pair.map do |k, v| {name: k}.merge!(v.to_h) end end def element_data element_store.each_pair.map do |k, v| {name: k}.merge!(v.to_h) end end def connect(name, &block) Session.new(**ftp_store[name], &block) end def test_ftp(name) config = ftp_store[name] Session.new(**config.to_h) { |ftp| raise Fail if ftp.closed? ftp.chdir(config.base_dir) } true end def test_uploading(name, dir_name = '') config = ftp_store[name] Session.new(**config.to_h) { |ftp| raise Fail if ftp.closed? ftp.chdir(config.base_dir) ftp.mkdir('_' + dir_name + '_' + DateTime.now.strftime('%Y%m%d_%H%M%S')) } true end def upload(name, force: false) case element_store[name] when Target upload_rendered(name, force: force) when FileTarget upload_file(name) else nil end end def upload_file(name) target = element_store[name] elements = target.files.map do |path_string| f = Pathname.new(path_string) path = if target.base_dir path = f.dup.to_s path.slice!(target.base_dir.to_s) path else f.basename end UploaderPart.new(local_file: f, path: target.dir + path) end Uploader.new(elements) end def upload_rendered(name, force: false) write_temp(name, force: force) target = element_store[name] keys = target.element_list.map { |t| target.key(t.try(:id)) } base_elements = if force Uploading .where { key.in keys } else Uploading .where { (key.in keys) & ((uploaded_at == nil) | (source_updated_at > uploaded_at)) } end elements = base_elements.map do |e| UploaderPart.new( uploading: e, path: e.path, local_file: local_file_path(e.path) ) end Uploader.new(elements) end def to(ftp_name, uploader_parts) config = ftp_store[ftp_name] Session.new(**config.to_h) { |ftp| uploader_parts.each do |part| part.configure!(config) unless part.ok? ftp.put(part.local_file, part.remote_file) part.update!(uploaded_at: DateTime.now) end } end def element_klass(name) element_store[name].klass end def element_list(name) element_store[name].element_list end def local_file_path(path) basic[:temp_dir] + path end def render_test(name) render(name) end def template_renderer(file) ->(record) { view = ActionView::Base.new(ActionController::Base.view_paths, {}) view.assign({record: record}) view.render(file: file) } end def detect_renderer(target) case when target.renderer target.renderer when target.template template_renderer(target.template) else default_renderer(target.klass) end end def preview(name, id) target = element_store[name] renderer = detect_renderer(target) element = target.pick(id) renderer.call(element) end # # render結果をDBに保持する # def render(name, force: false) target = element_store[name] renderer = detect_renderer(target) target.element_list.map do |element| key = target.key(element.try(:id)) uploading = Uploading.find_by(key: key) || Uploading.new element_day = element.try(:updated_at) if !force && uploading.source_updated_at && element_day && uploading.source_updated_at > element_day next uploading end p :update uploading.update!( key: key, path: target.path.call(element), body: renderer.call(element), written: false, source_updated_at: DateTime.now ) uploading end end # # render結果をファイルに書き出す # def write_temp(name, force: false) render(name, force: force).flatten.each do |target| if target.written next end target_path = local_file_path(target.path) FileUtils.mkdir_p(File.dirname(target_path)) File.write(target_path, target.body) target.update!(written: true) end end def default_renderer(klass) column_names = klass.column_names ->(record) { column_names.map { |name| value = record.send(name) "#{name} = #{value}" }.join('<br>').html_safe } end end def self.included(klass) klass.extend ClassMethods end end end
json.array!(@usuarios) do |usuario| json.extract! usuario, :id, :nome_completo, :apelido, :sexo, :email, :data_cadastro json.url usuario_url(usuario, format: :json) end
require './spec/spec_helper.rb' describe 'Registered users' do self.use_transactional_fixtures = false before :all do ensure_server_is_running DatabaseCleaner.clean end after :all do DatabaseCleaner.clean end describe 'User CRUD' do it 'should be editable' do ensure_logged_in_as 'admin' visit '/registered_users' body.should =~ /admin@test.com/ click_on 'Edit' fill_in 'Email', :with => '' click_on 'Update User' body.should =~ /Email can't be blank/ fill_in 'Email', :with => 'invalidemail' click_on 'Update User' body.should =~ /Email is invalid/ fill_in 'Email', :with => 'validemail@test.com' click_on 'Update User' body.should =~ /User was successfully updated./ body.should =~ /validemail@test.com/ end it 'should be destroyable' do user = User.create!(:email => 'foo@bar.com', :password => 'foobar') ensure_logged_in_as 'admin' visit '/registered_users' body.should =~ /foo@bar.com/ find(:xpath, "//a[@href='/registered_users/#{user.id}']").click page.driver.browser.switch_to.alert.accept body.should_not =~ /foo@bar.com/ end end end
class AreaSerializer < ActiveModel::Serializer attributes :id, :name, :status, :icon has_many :users end
class Player attr_reader :hp def initialize(name) @name = name @hp = 100 end def name @name end def is_attacked @hp -= 10 end end
class City attr_reader(:id,:name) define_method(:initialize)do |attributes| @id = attributes.fetch(:id) @name = attributes.fetch(:name) end define_method(:save)do result = DB.exec("INSERT INTO cities (name) VALUES ('#{name}') RETURNING id;") id = result.first().fetch('id').to_i @id = id end define_singleton_method(:all)do cities = [] result = DB.exec("SELECT * FROM cities;") result.each()do |city| id = city.fetch('id') name = city.fetch('name') new_city = City.new(:id,:name) cities.push(new_city) end cities end define_singleton_method(:delete)do |id| DB.exec("DELETE FROM cities WHERE id=#{id};") end end
require "horseman/browser" describe Horseman::Browser::Browser do include Doubles subject { described_class.new(connection, js_engine, "http://www.example.com")} it "saves cookies" do expect(subject.cookies).to be_empty subject.get! expect(subject.cookies.count).to eq 2 expect(subject.cookies["name1"]).to eq "value1" expect(subject.cookies["name2"]).to eq "value2" expect(subject.connection).to receive(:exec_request) do |request| expect(request["cookie"]).to match /\w+=\w+; \w+=\w+/ expect(request["cookie"]).to match /name1=value1/ expect(request["cookie"]).to match /name2=value2/ response end subject.get! end it "empties the cookies when the session is cleared" do subject.get! expect(subject.cookies).not_to be_empty subject.clear_session expect(subject.cookies).to be_empty end it "stores information about the last response" do subject.get! expect(subject.last_action.response.body).to eq html end context "when javascript is enabled" do subject {described_class.new(connection, js_engine, "http://www.example.com", :enable_js => true)} it "executes javascript" do expect(subject.js_engine).to receive(:execute) { |body, scope| expect([%{alert("downloaded");}, %{alert("hello");}, %{alert("no type");}]).to include(body) }.exactly(3).times subject.get! end end context "when processing redirects" do def build_browser(options) code = options[:code] || "200" num_redirects = options[:redirects] || 1 location = options[:location] r = response(:location => location) redirects = 0 allow(r).to receive(:code) do code = (redirects >= num_redirects) ? "200" : code redirects += 1 code end c = connection allow(c).to receive(:exec_request) { r } described_class.new(c, js_engine, "http://www.example.com") end def should_redirect(options) browser = build_browser(options) expected_url = options[:expected_url] || "http://www.anotherdomain.com/path" redirects = 0 expect(browser.connection).to receive(:build_request).twice do |options| browser.connection.url = options[:url] if redirects > 0 expect(options[:url]).to eq expected_url end redirects += 1 request end browser.get! end it "follows 301s" do should_redirect(:code => "301") end it "follows 302s" do should_redirect(:code => "302") end it "follows 303s" do should_redirect(:code => "303") end it "follows 307s" do should_redirect(:code => "307") end it "follows relative paths" do should_redirect(:code => "301", :location => "redirect", :expected_url => "http://www.example.com/redirect") end it "raises an error after 10 consecutive redirects" do good_browser = build_browser(:code => "301", :redirects => 10) good_browser.get! bad_browser = build_browser(:code => "301", :redirects => 11) expect { bad_browser.get! }.to raise_error end end context "when posting" do def describe_url count = 0 expect(subject.connection).to receive(:build_request).twice do |options| subject.connection.url = options[:url] yield options[:url] if (count > 0) count += 1 request end post end def describe_request expect(subject.connection).to receive(:exec_request).twice do |request| if (request.method == "POST") yield request end response end post end it "raises an error on invalid form id" do expect { subject.post!("/", :form => :bad_form) }.to raise_error end context "with a relative action" do def post subject.post!("/path", :form => :form1) end it "constructs the correct URL" do describe_url do |url| expect(url).to eq "http://www.example.com/action" end end end context "with an absolute action" do def post subject.post!("/path", :form => :form2) end it "constructs the correct URL" do describe_url do |url| expect(url).to eq "http://www.anotherdomain.com/action" end end end context "with no action" do def post subject.post!("/path", :form => :form3) end it "constructs the correct URL" do describe_url do |url| expect(url).to eq "http://www.example.com/path" end end end context "with unchecked checkboxes" do def post subject.post!("/path", :form => :form1, :data => {:text => "text_value"}, :unchecked => [:check]) end it "does not include unchecked checkboxes" do describe_request do |request| expect(request.body).not_to match /name="check"/ end end end context "multipart data" do def post subject.post!("/", :form => :form1, :data => {:text => "text_value", :check => "checkbox_value"}) end it "properly sets content type" do describe_request do |request| expect(request["Content-Type"]).to eq "multipart/form-data; boundary=#{subject.multipart_boundary}" end end it "properly encodes form data" do describe_request do |request| expect(request.body).to match /\A--#{subject.multipart_boundary}.*--#{subject.multipart_boundary}--\Z/m expect(request.body).to match /^--#{subject.multipart_boundary}\r\nContent-Disposition: form-data; name="text"\r\n\r\ntext_value/m expect(request.body).to match /^--#{subject.multipart_boundary}\r\nContent-Disposition: form-data; name="check"\r\n\r\ncheckbox_value/m end end end context "URL encoded data" do def post subject.post!("/", :form => :form2, :data => {:text1 => "value1", :text2 => "value2"}) end it "properly sets content type" do describe_request do |request| expect(request["Content-Type"]).to eq "application/x-www-form-urlencoded" end end it "properly encodes form data" do describe_request do |request| expect(request.body).to match /\w+=\w+&\w+=\w+/ expect(request.body).to match /text1=value1/ expect(request.body).to match /text2=value2/ end end end end end
class BallotEntry < ActiveRecord::Base belongs_to :ballot validates_uniqueness_of :rank, scope: :ballot_id def candidate=(candidate) self.candidate_id = candidate.id self.save! end def candidate return Candidate.find(self.candidate_id) end def eql?(other) self.candidate_id.eql? other.candidate_id and self.rank.eql? other.rank end end
class CreateJoinTableUserRaid < ActiveRecord::Migration[5.2] def change create_join_table :users, :raids do |t| t.index [:user_id, :raid_id] t.index [:raid_id, :user_id] end end end
# frozen_string_literal: true class Rogare::Commands::Hello extend Rogare::Command command 'hello', hidden: true match_command /.+/, method: :execute match_empty :execute def execute(m) this_server = m.channel.server servers, needs_prefix = if this_server [{ 0 => this_server }, false] else [Rogare.discord.servers, true] end servers.each do |_id, server| if ENV['RACK_ENV'] == 'production' && server.name == 'sassbot-test' logs 'skip sassbot test server in production' next end member = m.user.discord.on(server) person = server.roles.find { |role| role.name == 'person' } prefix = ("[**#{server.name}**]" if needs_prefix) unless person m.reply "No **person** role on #{prefix || 'here'}, tell the server admins!" next end begin if member.roles.any? { |role| role.id == person.id } if needs_prefix m.reply "#{prefix} You’re already all good here, but thanks for saying hi." else m.reply 'You can already speak in here! And hello to you too' end else member.add_role(person, 'Said hello to the bot') m.reply "#{prefix} You may speak! Thank you! Enjoy yourself!" end rescue StandardError => e m.reply "Something went wrong! Tell the #{prefix} admins!" logs "!!! Missing role-management permissions for #{server.name}???\n#{e}" end end end end
# frozen_string_literal: true class CreateProfiles < ActiveRecord::Migration[5.2] def change create_table :profiles do |t| t.references :user t.string :name t.string :second_name t.string :surname t.integer :phone t.integer :country_code t.string :email t.integer :passport_code t.integer :passport_number t.date :passport_date_issue t.string :passport_issuer t.integer :notification_number t.integer :notification_code t.integer :inn t.date :dob t.timestamps end end end
# # 最も高値でフィギュアを売れるセットの組み合わせを算出します。 # 実行例) ruby sales_doll.rb 10 # # 各セットの価格リスト set_price_list = [1, 6, 8, 10, 17, 18, 20, 24, 26, 30] # 各セットの単価リスト set_unit_list = {} set_unit_list_sort = {} # 売却残個数 nokori = ARGV[0].to_i # 売却セット組み合わせ set_pattern = [] # 売却額 price = 0 # 各セットの単価を算出する set_price_list.each_with_index do |price, idx| unit = (price / (idx + 1.0)).round(1) set_unit_list[idx + 1] = unit; end # 算出した単価を降順でソートする set_unit_list.sort_by{|key, value| -value}.each do |key, value| set_unit_list_sort[key] = value end # 最も高値のセットを組みあせていく while nokori > 0 do set_unit_list_sort.each do |key, unit| if nokori >= key nokori -= key set_pattern.push key price += set_price_list[key - 1] break end end end p "pattern : #{set_pattern.join(', ')}" p "price : #{price}"
# reverse_it.rb # Write a method that takes one argument, a string, and returns a # new string with the words in reverse order. # Pseudo-code: # Create a mirror image of a string by flipping it. # First word will equal the last word. # Need to split the string into individual words. # Once split, the words can be placed in an array object. # Then I can run a loop that takes the last element of the array and # adds it to a string, each time the loop iterates a new word is added. # Formal pseudo-code: # START by defining method `reverse_sentence(string)`; # READ the `string` and split it into individual words; # SET the individual words in a new array; # SET a new empty string variable; # Perform an IF/ELSE loop; # IF empty string variable is empty, take last word of array # and assign it to the variable. # ELSE take the last word of array and add it to the non-empty # string. def reverse_sentence(string) split_str = string.split empty_str = "" while split_str != [] if empty_str == "" empty_str = split_str.pop else empty_str << " " + split_str.pop end end empty_str end puts reverse_sentence('') == '' puts reverse_sentence('Hello World') == 'World Hello' puts reverse_sentence('Reverse these words') == 'words these Reverse' puts "------" # Launch School solution: def reverse_sentence(string) string.split.reverse.join(' ') end puts reverse_sentence('') == '' puts reverse_sentence('Hello World') == 'World Hello' puts reverse_sentence('Reverse these words') == 'words these Reverse'
Rails.application.routes.draw do resources :opinions devise_for :users resources :users, only: %i[index show] resources :follows root 'opinions#index' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
# frozen_string_literal: true require 'openid_connect' module UMA module Discovery class Config class Response < OpenIDConnect::Discovery::Provider::Config::Response unavailable_attributes = %i[subject_types_supported id_token_signing_alg_values_supported] undef_required_attributes(*unavailable_attributes) _validators.transform_values! do |validators| validators.map { |validator| unavailable_attributes.each(&validator.attributes.method(:delete)); validator } end uma_uri_attributes = { required: [ :resource_registration_endpoint, :permission_endpoint, :policy_endpoint ], optional: [] } attr_required(*uma_uri_attributes[:required]) end end end end
require_relative 'author' class Post include Datamappify::Entity attribute :title, String attributes_from Author, :prefix_with => :author end
class CreateSearches < ActiveRecord::Migration[5.1] def change create_table :searches do |t| t.string :keywords t.date :date_of_birth t.string :address t.integer :phone_no t.string :infection t.string :injury t.integer :min_consultation t.integer :max_consultation t.timestamps end end end
class CreditCard < ActiveRecord::Base belongs_to :user has_many :orders validates :ccv, :expiration_month, :expiration_year, :first_name, :last_name, presence: true end
class Tweet < ApplicationRecord belongs_to :user validates :text, presence: true, length: 1..280 validates :user, presence: true end
module Indexable extend ActiveSupport::Concern included do include Elasticsearch::Model include Elasticsearch::Model::Callbacks # include ElasticsearchSearchable __elasticsearch__.client = Elasticsearch::Client.new host: Settings.elasticsearch.urls settings index: { number_of_shards: 3 } do mappings dynamic: 'true' end def self.search(query_or_definition, options={}) options.merge!({size: 100}) __elasticsearch__.search(query_or_definition, options) end after_save ->(klass) { IndexerJob.perform_later(klass) } after_update ->(klass) { IndexUpdaterJob.perform_later(klass) } after_destroy ->(klass) { UnindexerJob.perform_later(klass) } end end
class SalesPage < GenericBasePage include DataHelper #class HeaderPage < GenericBasePage element(:regions) {|b| b.link(text: "Regions")} end
class CreatePhrases < ActiveRecord::Migration[5.1] def change create_table :phrases do |t| t.string :label t.string :abbrev t.text :text t.belongs_to :user t.timestamps end end end
class UsersController < ApplicationController skip_before_action :require_login, except: [:destroy] def new end def create user = Users::UserCreateFacade.new( email: params[:email], password: params[:password], first_name: params[:first_name], last_name: params[:last_name], ).run flash[:success] = "Account for #{user.email} successfully created" redirect_to user_sessions_path rescue Users::UserCreateFacade::UserAlreadyExists flash[:danger] = "Account for email already exists" redirect_to new_user_sessions_path end end
FactoryBot.define do factory :change_image do file { Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'fluffy_cat.jpg'), 'image/png') } user { create :user } end end
class IdeasController < ApplicationController before_action :set_idea, only: %i[show edit update destroy] before_action :set_user def index @ideas = Idea.all end def show @images = @idea.images end def new @categories = Category.all @idea = Idea.new end def create @categories = Category.all @idea = @user.ideas.new(ideas_params) if @idea.save flash[:success] = "#{@idea.title} created!" redirect_to user_idea_path(@user, @idea) else render :new end end def edit @categories = Category.all end def update if params[:image_id] @idea.images << Image.find(params[:image_id]) redirect_to user_idea_path(current_user, @idea) else @idea.update(ideas_params) if @idea.save flash[:success] = "#{@idea.title} Updated!" redirect_to user_idea_path(@user, @idea) else render :edit end end end def destroy @idea.destroy flash[:success] = "#{@idea.title} Deleted!" redirect_to user_path(@user) end private def ideas_params params.require(:idea).permit(:title, :content, :category_id) end def set_idea @idea = Idea.find(params[:id]) end def set_user @user = User.find(params[:user_id]) end end
# -*- encoding : utf-8 -*- class CreateMessages < ActiveRecord::Migration def change create_table :messages do |t| t.text :question t.text :reply t.datetime :replied_at t.references :student t.references :course t.timestamps end add_index :messages, :student_id add_index :messages, :course_id end end
include_recipe 'directory_helper' home_dir = DirectoryHelper.home(node) execute "Install rustup" do user node[:user] command "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y" end home_path = "#{home_dir}/" + node[:user] cargo_bin_path = home_path + "/.cargo/bin" set_cargo_bin_to_path = "PATH=" + cargo_bin_path + ":$PATH" node[:rust][:versions].each do |version| execute "Install rust #{version}" do user node[:user] command "#{set_cargo_bin_to_path} rustup install #{version}" end end node[:rust][:global].tap do |version| execute "Set default to #{version}" do user node[:user] command "#{set_cargo_bin_to_path} rustup default #{version}" end end node[:rust_packages].each do |package| execute "Install rust package: #{package}" do user node[:user] command "#{set_cargo_bin_to_path} cargo install --locked #{package}" end end execute "Update rust packages" do user node[:user] command "#{set_cargo_bin_to_path} cargo install-update --all" end
require 'rails_helper' RSpec.describe Mealbook, type: :model do it { should belong_to :owner } it { should have_many :meals } it { should validate_presence_of :mealbook_name } it { should respond_to :public } end
class CreateNominates < ActiveRecord::Migration def change create_table :nominates do |t| t.integer :user_id, null: false t.string :candidate, null: false, limit: 32 t.string :reason, null: false, limit: 140 t.timestamps end end end
module Refinery module Properties class Engine < Rails::Engine include Refinery::Engine isolate_namespace Refinery::Properties engine_name :refinery_properties initializer "register refinerycms_area_codes plugin" do Refinery::Plugin.register do |plugin| plugin.name = "area_codes" plugin.url = proc { Refinery::Core::Engine.routes.url_helpers.properties_admin_area_codes_path } plugin.pathname = root plugin.activity = { :class_name => :'refinery/properties/area_code', :title => 'name' } plugin.menu_match = %r{refinery/properties/area_codes(/.*)?$} end end config.after_initialize do Refinery.register_extension(Refinery::AreaCodes) end end end end
class RetailController < InheritedResources::Base before_filter :auto_sign_in layout 'retail' protected def auto_sign_in sign_in(:customer, Customer.anonymous) unless customer_signed_in? if (cart_id = session.delete(:cart_id)) and current_customer.cart.blank? begin Cart.find(cart_id).assign_customer(current_customer) rescue ActiveRecord::RecordNotFound end end end end