text
stringlengths
10
2.61M
class Transaction < ApplicationRecord belongs_to :category belongs_to :user has_many :bills validates :date, presence: true validates :name, presence: true # validates :category_id, presence: true validates :amount, { presence: true, numericality: true } validates :paid, {inclusion: { in: [true, false]}, exclusion: {in: [nil]}} accepts_nested_attributes_for :category, reject_if: :no_name def no_name(attributes) attributes[:name].blank? end end
describe 'GITPackCollection' do before do @err = Pointer.new(:object) @collection = GITPackCollection.collectionWithContentsOfDirectory("#{TEST_REPO}/.git/objects/pack", error:@err) end should 'not be nil' do @collection.should.not.be.nil end should 'not have an error' do @err[0].should.be.nil end describe '-unpackObjectWithSha1:error:' do before do @sha = GITObjectHash.objectHashWithString("6c20014aaa67fc2ac4958f899b6d5494cb30331f") @obj = @collection.unpackObjectWithSha1(@sha, error:@err) end should 'not be nil' do @obj.should.not.be.nil end should 'not have an error' do @err[0].should.be.nil end should 'have found the correct object' do @obj.sha1.unpackedString.should == @sha.unpackedString end end end
require_relative "../../business/engines/validators" RSpec.describe Validators::Presence do describe "#with?" do context "a nil value" do subject { described_class.new(:name) } it "should be invalid" do expect(subject.with?(nil)).to eql false end end context "an empty string" do subject { described_class.new(:name) } it "should be invalid" do expect(subject.with?("")).to eql false end end context "an non empty string" do subject { described_class.new(:name) } it "should be invalid" do expect(subject.with?("non empty")).to eql true end end context "an integer" do subject { described_class.new(:name) } it "should be valid" do expect(subject.with?(13)).to eql true end end context "an float" do subject { described_class.new(:name) } it "should be valid" do expect(subject.with?(92.37)).to eql true end end end end RSpec.describe Validators::Uniqueness do describe "#with?" do context "given a nil value" do subject { described_class.new(:name) } it "should be valid" do expect(subject.with?(nil, scope([]))).to eql true end end context "given an empty string" do subject { described_class.new(:name) } it "should be valid" do expect(subject.with?("", scope([]))).to eql true end end context "given an existing value" do subject { described_class.new(:name) } it "should not be valid" do expect(subject.with?("exists", scope(["exists"]))) .to eql false end end context "given a non existing value" do subject { described_class.new(:name) } it "should be valid" do expect(subject.with?("doesnt-exists", scope([]))) .to eql true end end end def scope(value) Class.new.tap do |obj| allow(obj).to \ receive(:where).and_return(value) end end end RSpec.describe Validators::Size do describe "#with?" do context "a nil value" do subject { described_class.new(:episodes, 3) } it "should not be valid" do expect(subject.with?(nil)).to eql false end end context "an empty string" do subject { described_class.new(:episodes, 3) } it "should not be valid" do expect(subject.with?("")).to eql false end end context "an short string" do subject { described_class.new(:episodes, 7) } it "should not be valid" do expect(subject.with?("short")).to eql false end end context "an exact sized string" do subject { described_class.new(:episodes, 5) } it "should be valid" do expect(subject.with?("exact")).to eql true end end context "a bigger string" do subject { described_class.new(:episodes, 5) } it "should be valid" do expect(subject.with?("big-big-big")).to eql true end end end end
# frozen_string_literal: true def ordinalize(num) if !num.abs.between?(1, 3) num.to_s + 'th' else case num.abs when 1 then num.to_s + 'st' when 2 then num.to_s + 'nd' when 3 then num.to_s + 'rd' end end end
class ControlpltktsController < ApplicationController before_action :set_controlpltkt, only: [:show, :edit, :update, :destroy] # GET /controlpltkts # GET /controlpltkts.json def index @controlpltkts = Controlpltkt.all end # GET /controlpltkts/1 # GET /controlpltkts/1.json def show end # GET /controlpltkts/new def new @controlpltkt = Controlpltkt.new end # GET /controlpltkts/1/edit def edit end # POST /controlpltkts # POST /controlpltkts.json def create @controlpltkt = Controlpltkt.new(controlpltkt_params) respond_to do |format| if @controlpltkt.save format.html { redirect_to @controlpltkt, notice: 'Controlpltkt was successfully created.' } format.json { render :show, status: :created, location: @controlpltkt } else format.html { render :new } format.json { render json: @controlpltkt.errors, status: :unprocessable_entity } end end end # PATCH/PUT /controlpltkts/1 # PATCH/PUT /controlpltkts/1.json def update respond_to do |format| if @controlpltkt.update(controlpltkt_params) format.html { redirect_to @controlpltkt, notice: 'Controlpltkt was successfully updated.' } format.json { render :show, status: :ok, location: @controlpltkt } else format.html { render :edit } format.json { render json: @controlpltkt.errors, status: :unprocessable_entity } end end end # DELETE /controlpltkts/1 # DELETE /controlpltkts/1.json def destroy @controlpltkt.destroy respond_to do |format| format.html { redirect_to controlpltkts_url, notice: 'Controlpltkt was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_controlpltkt @controlpltkt = Controlpltkt.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def controlpltkt_params params.require(:controlpltkt).permit(:n1, :n2, :siglas, :limite, :vendida) end end
require 'rspec' require 'towers_of_hanoi' describe '#Towers_of_hanoi' do let (:game) { Towers_of_hanoi.new } describe '#initialize' do it 'stacks should contain 3 stacks' do expect(game.stacks.length).to eq(3) end it 'stacks should have three disks' do expect(game.stacks[1].length).to eq(3) end it 'second and third stacks should be empty' do expect(game.stacks[2].length).to eq(0) expect(game.stacks[3].length).to eq(0) end end describe '#move_disk' do it 'should move to last disk of new stack' do disk = game.stacks[1].last game.move_disk(1, 2) expect(game.stacks[2].last).to eq(disk) end it "shouldn't put a larger disk on a smaller disk" do game.move_disk(1, 2) expect { game.move_disk(1, 2) }.to raise_error("You can't put a larger disk on a smaller disk") end it "shouldn't be able to move from an empty stack" do expect { game.move_disk(2, 1) }.to raise_error("You can't remove from an empty stack") end end describe '#won?' do it 'should return false when game incomplete' do expect(game.won?).to be(false) end it 'should return true when game complete in third stack' do hash = { 1 => [], 2 => [], 3 => [3, 2, 1] } winning_game = Towers_of_hanoi.new(hash) expect(winning_game.won?).to be(true) end it 'should return true when game complete in second stack' do hash = { 1 => [], 2 => [3, 2, 1], 3 => [] } winning_game = Towers_of_hanoi.new(hash) expect(winning_game.won?).to be(true) end end end
# encoding: UTF-8 class EEKonto < ActiveRecord::Base set_table_name "EEKonto" attr_accessible :ktoNr, :bankId, :kreditlimit set_primary_key :ktoNr belongs_to :OZBKonto belongs_to :Bankverbindung has_one :ZEKonto, :foreign_key => :ktoNr # Done, getestet def validate! errors = ActiveModel::Errors.new(self) # Kontonummer if self.ktoNr.nil? then errors.add("", "Bitte geben sie eine Kontonummer an.") else if !self.ktoNr.to_s.match(/[0-9]+/) then errors.add("", "Die Kontonummer muss eine Zahl sein.") end end # Bankverbindung if self.bankId.nil? then errors.add("", "Bitte geben sie eine Bankverbindung an.") end # Kreditlimit if self.kreditlimit.nil? then errors.add("", "Bitte geben sie ein gültiges Kreditlimit (>0) an.") else if !self.kreditlimit.to_s.match(/[0-9]+/) then errors.add("", "Bitte geben sie einen gültigen Zahlenwert > 0 an.") else if self.kreditlimit < 0 then errors.add("", "Bitte geben Sie einen positiven Zahlenwert für das Kreditlimit an.") end end end return errors end end
class CrabCups def initialize(cups) @idx = 0 @len = cups.length @cups = cups.chars.map(&:to_i) end def move label = cur_label = @cups[@idx] picks = [@cups[(@idx + 1) % @len], @cups[(@idx + 2) % @len], @cups[(@idx + 3) % @len]] @cups.reject!{|num| picks.include?(num)} label = next_cup_label(label) until label != cur_label && !picks.include?(label) dest = @cups.index(label) #puts "destination: #{label}" @cups.insert((dest + 1) % @len, *picks) @idx = (@cups.index(cur_label) + 1) % @len end def move_all(num) num.times { move } idx = @cups.index(1) 1.upto(@len - 1).map{|num| @cups[(idx + num) % @len]}.join end def print puts @cups.map.with_index{|cup, i| i == @idx ? "(#{cup})" : "#{cup}"}.join(' ') end def next_cup_label(cup) cup == 1 ? 9 : cup - 1 end end puts "Hopefully 92658374" puts CrabCups.new('389125467').move_all(10) puts "Hopefully 67384529" puts CrabCups.new('389125467').move_all(100) puts "First star" puts CrabCups.new('716892543').move_all(100)
# Instructions # ------------------------------------------------------------------------------ # This file is in the same format as your assessments. # # You have 1 hour for this assessment. Give yourself about 15 minutes per problem. # Move on if you get stuck # # Everything should print 'true' when you run the file. When time is up, make # sure you don't have any unexpected `end`s or infinite loops that would keep your # code from running. # # This assessment is strictly closed notes. No paper notes and no internet! # # Look at the test cases below the problem before you approach it. # ------------------------------------------------------------------------------ # In Order # Define a boolean method, #in_order?(array), that accepts an array of integers # as an argument. This method should return true if elements in the array are # in order from smallest to largest (left to right), and false otherwise. def in_order?(array) end puts "-------In Order-------" puts in_order?([1, 2, 3]) == true puts in_order?([1, 2, 2, 10]) == true puts in_order?([3, 6, 4, 7]) == false puts in_order?([-10, -2, 0, 23, 101]) == true # ------------------------------------------------------------------------------ # Boolean to Binary # Define a method, #boolean_to_binary(array), that accepts an array of booleans as # an argument. Your method should convert the array into a string made entirely # of 1s and 0s. A true should become a "1" and a false should become a "0". def boolean_to_binary(array) end puts "-------Boolean to Binary-------" puts boolean_to_binary([true]) == "1" puts boolean_to_binary([false]) == "0" puts boolean_to_binary([true, false, true]) == "101" puts boolean_to_binary([false, true, true, false, true, true]) == "11011" # ------------------------------------------------------------------------------ # More Vowels # Define a method, #more_vowels(string1, string2), that accepts two strings as # arguments. Your method should return the string with more vowels. Return "tie" # if the words have the same number of vowels. (Hint: define a helper method!) def more_vowels(string1, string2) end puts "-------More Vowels-------" puts more_vowels("aaa", "ee") == "aaa" puts more_vowels("abcdefghi", "bcdfgh") == "abcdefghi" puts more_vowels("woodchuck", "spaghetti") == "tie" puts more_vowels("alphabetical", "serendipity") == "alphabetical" # ------------------------------------------------------------------------------ # Fibonacci Sequence # The Fibonacci Sequence follows a simple rule: the next number in the sequence is the sum # of the previous two. The sequence starts with [0, 1]. We then compute the 3rd # number by summing the first & the second: 0 + 1 == 1. This yields [0, 1, 1]. We compute # the 4th number by summing the second and the third: 1 + 1 == 2... and the pattern # continues # Define a method, #fibs, that accepts an integer as an argument. The method should # return an array of the first n Fibonacci numbers. # # fibs(6) => [0, 1, 1, 2, 3, 5] def fibs(n) end puts "-------Fibonacci-------" puts fibs(0) == [] puts fibs(1) == [0] puts fibs(3) == [0, 1, 1] puts fibs(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
class ConcreteHolidays::LaborDay include ConcreteHolidays::Calculations def self.date(year) # the first Monday of September this_or_next(:mon, Date.new(year,9,1)) end end
class CreateTestPapersTestPapers < ActiveRecord::Migration def up create_table :refinery_test_papers do |t| t.integer :wine_id t.integer :user_id t.integer :group_id t.string :score t.datetime :drink_begin_at t.datetime :drink_end_at t.text :note t.integer :position t.timestamps end end def down if defined?(::Refinery::UserPlugin) ::Refinery::UserPlugin.destroy_all({:name => "refinerycms-test_papers"}) end if defined?(::Refinery::Page) ::Refinery::Page.delete_all({:link_url => "/test_papers/test_papers"}) end drop_table :refinery_test_papers end end
class AddFieldsToOrders < ActiveRecord::Migration def change add_column :orders, :buyer_id, :integer add_column :orders, :seller_id, :integer end end
require "application_system_test_case" class SharedImagesTest < ApplicationSystemTestCase setup do @shared_image = shared_images(:one) end test "visiting the index" do visit shared_images_url assert_selector "h1", text: "Shared Images" end test "creating a Shared image" do visit shared_images_url click_on "New Shared Image" fill_in "Food", with: @shared_image.food_id fill_in "Url", with: @shared_image.url fill_in "User", with: @shared_image.user_id click_on "Create Shared image" assert_text "Shared image was successfully created" click_on "Back" end test "updating a Shared image" do visit shared_images_url click_on "Edit", match: :first fill_in "Food", with: @shared_image.food_id fill_in "Url", with: @shared_image.url fill_in "User", with: @shared_image.user_id click_on "Update Shared image" assert_text "Shared image was successfully updated" click_on "Back" end test "destroying a Shared image" do visit shared_images_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Shared image was successfully destroyed" end end
class AddExchangeRateToDelivery < ActiveRecord::Migration def up add_column :deliveries, :exchange_rate, :decimal, :precision => 8, :scale => 2 end def down remove_column :deliveries, :exchange_rate end end
require 'spec_helper' describe Kuhsaft::TwoColumnBrick, type: :model do let :two_column_brick do Kuhsaft::TwoColumnBrick.new end describe '#user_can_add_childs?' do it 'returns false' do expect(two_column_brick.user_can_add_childs?).to be_falsey end end describe '#user_can_delete?' do it 'returns true' do expect(two_column_brick.user_can_delete?).to be_truthy end end describe '#user_can_save?' do it 'returns true' do expect(two_column_brick.user_can_save?).to be_truthy end end describe '#renders_own_childs?' do it 'returns true' do expect(two_column_brick.renders_own_childs?).to be_truthy end end describe '#partitioning' do context 'when no partition is set' do it 'returns 0 (50/50)' do expect(two_column_brick.partitioning).to be(0) end end context 'when the partition is set' do it 'returns the value' do two_column_brick.partitioning = 1 expect(two_column_brick.partitioning).to be(1) end end end describe '.partitionings' do it 'returns the 3 default partitions' do expect(Kuhsaft::TwoColumnBrick.partitionings.size).to eq(3) end end describe '#create' do it 'creates two single columns as childs' do two_column_brick.save expect(two_column_brick.bricks).to be_all { |brick| expect(brick).to be_a(Kuhsaft::ColumnBrick) } end end describe '#bricks' do it 'can have childs' do expect(two_column_brick).to respond_to(:bricks) end end describe '#to_style_class' do it 'adds the row class to the default styles' do expect(Kuhsaft::TwoColumnBrick.new.to_style_class).to eq('kuhsaft-two-column-brick row-fluid') end end describe '#add_columns' do it 'sets the position of the first column brick to 1' do expect(Kuhsaft::TwoColumnBrick.new.send(:add_columns).to_a.first.position).to eq(1) end it 'sets the position of the second column brick to 2' do expect(Kuhsaft::TwoColumnBrick.new.send(:add_columns).to_a.second.position).to eq(2) end end end
class MoneyAccount < ActiveRecord::Base # Define the account types like credit cards, line of credit, etc. ACCOUNT_TYPES = [ { id: 1, name: 'Cuenta Corriente', credit: false }, { id: 2, name: 'Inversiones', credit: false }, { id: 3, name: 'Línea de Crédito', credit: true }, { id: 4, name: 'Tarjeta de Crédito', credit: true } ] # Associations belongs_to :account, dependent: :destroy # Validations validates_presence_of :name, :number, :bank_name, :account_id, :type_id # Devuelve si la cuenta es del tipo credito, como Visa # Esto depende del tipo de cuenta def credit? MoneyAccount.types_as_hash[type_id.to_s][:credit] end # Return an array of MoneyAccountTypes def self.types ACCOUNT_TYPES.map do |type| OpenStruct.new type end end def self.types_as_hash hash = {} ACCOUNT_TYPES.each do |type| tmp = type.dup hash[tmp.delete(:id).to_s] = tmp end hash end end
require "application_system_test_case" class AddtaxisTest < ApplicationSystemTestCase setup do @addtaxi = addtaxis(:one) end test "visiting the index" do visit addtaxis_url assert_selector "h1", text: "Addtaxis" end test "creating a Addtaxi" do visit addtaxis_url click_on "New Addtaxi" fill_in "Holdername", with: @addtaxi.Holdername fill_in "Phone", with: @addtaxi.Phone fill_in "Registration", with: @addtaxi.Registration fill_in "Taxi", with: @addtaxi.Taxi fill_in "Vehicle", with: @addtaxi.Vehicle fill_in "Number", with: @addtaxi.number click_on "Create Addtaxi" assert_text "Addtaxi was successfully created" click_on "Back" end test "updating a Addtaxi" do visit addtaxis_url click_on "Edit", match: :first fill_in "Holdername", with: @addtaxi.Holdername fill_in "Phone", with: @addtaxi.Phone fill_in "Registration", with: @addtaxi.Registration fill_in "Taxi", with: @addtaxi.Taxi fill_in "Vehicle", with: @addtaxi.Vehicle fill_in "Number", with: @addtaxi.number click_on "Update Addtaxi" assert_text "Addtaxi was successfully updated" click_on "Back" end test "destroying a Addtaxi" do visit addtaxis_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Addtaxi was successfully destroyed" end end
class UserImagesController < ImagesController protected def load_entity @entity = User.find(params[:user_id]) end end
module ApplicationHelper end module Inspirer class MarkovModel def initialize @markov_model = Hash.new { |hash, key| hash[key] = [] } songs = Song.all songs.each do |song| tokens = tokenize(song.lyrics) until tokens.empty? token = tokens.pop markov_state = [tokens[-2], tokens[-1]] @markov_model[markov_state] << token end end end def complete_sentence(sentence = '', min_length: 5, max_length: 20) tokens = tokenize(sentence) until sentence_complete?(tokens, min_length, max_length) markov_state = [tokens[-2], tokens[-1]] tokens << @markov_model[markov_state].sample end tokens.join(' ').strip end private def tokenize(sentence) return [] if sentence.nil? || sentence.length == 0 sentence.split(' ').map { |word| word.downcase.to_sym } end def sentence_complete?(tokens, min_length, max_length) tokens.length >= max_length || tokens.length >= min_length && ( tokens.last.nil? || tokens.last =~ /[\!\?\.]\z/ ) end end end
module Entities class ListEntity < Grape::Entity expose :id expose :name expose :created_at expose :items, using: Entities::ItemEntity end end
module Api::V1 class ListSerializer < ActiveModel::Serializer attributes :name, :category def category object.category_cd end end end
class ProductImage < ApplicationRecord validates_presence_of :image_url, :product_id belongs_to :product, optional: true mount_uploader :image_url, ImageUploader end
module DatabaseTheory class FunctionnalDependency attr_accessor :determinant, :dependent # Build a +FunctionnalDependency+ object # +determinant+:: +String+ object representing the determinant set (comma separated) # +dependent+:: +String+ object representing the dependent set (comma separated) def initialize(determinant, dependent = '') @determinant, @dependent = determinant.split(","), dependent.split(",") end def determinant_singleton? @determinant.size == 1 end # Return each uniq attributes of the functonnal dependency def unique_attributes (@determinant | @dependent) end end end
require 'rails_helper' RSpec.describe DailyReport, :type => :model do before do @daily_report = FactoryGirl.create(:daily_report) end subject {@daily_report} describe "With valid data" do it "should be valid" do is_expected.to be_valid end it "should respond to date_recieved" do is_expected.to respond_to(:date_recieved) end it "should respond to content" do is_expected.to respond_to(:content) end it "should respond to date" do is_expected.to respond_to(:date) end it "should respond to created_at" do is_expected.to respond_to(:created_at) end it "should respond to updated_at" do is_expected.to respond_to(:updated_at) end it "should respond to employee" do is_expected.to respond_to(:employee) end end describe "with invalid data" do it "should not be valid" do expect(FactoryGirl.build(:daily_report, date_recieved: nil)).not_to be_valid expect(FactoryGirl.build(:daily_report, content: nil)).not_to be_valid expect(FactoryGirl.build(:daily_report, date: nil)).not_to be_valid expect(FactoryGirl.build(:daily_report, employee_id: nil)).not_to be_valid end end end
class AddTagToBills < ActiveRecord::Migration[6.0] def change add_column :bills, :tag, :string end end
class Viewpoints::Acts::Moderateable::ContentDocument < ActiveRecord::Base include AASM belongs_to :owner, :polymorphic => true has_many :content_fields has_many :content_histories validate :rejection_requires_code, :codes_requires_rejection named_scope :filter_status, lambda { |s| s.blank? ? {} : { :conditions =>{ :status => s}} } named_scope :filter_requires_review, lambda { |r| return {} if r.blank? { :conditions => r == "true" ? "requires_review is true" : "not requires_review is true" } } named_scope :filter_owner_id, lambda { |i| i.blank? ? {} : { :conditions =>{ :owner_id => i}} } named_scope :filter_owner_type_and_cobrand, lambda { |t, c| t.blank? ? {} : { :joins => "JOIN #{t.constantize.table_name} ON owner_id = #{t.constantize.table_name}.id", :conditions =>"owner_type='#{t}' AND #{t.constantize.table_name}.cobrand_id=#{c.id}"} } named_scope :filter_pending_profanities, lambda { |n| n.blank? ? { } : { :joins => { :content_fields => :filtered_words}, :conditions => "filtered_words.origin_type = content_documents.owner_type AND filtered_words.origin_id = content_documents.owner_id AND filtered_words.status='new'"} } after_create :journal_state #setup the state machine aasm_column 'status' aasm_initial_state :new aasm_state :new aasm_state :quarantined, {:enter=>Proc.new { |obj| obj.comment||='Document quarantined'}} aasm_state :pending_review aasm_state :active, {:enter=>Proc.new { |content_doc| if content_doc.owner.status == "new" or content_doc.owner.status == "quarantined" content_doc.owner.after_initial_activation[content_doc] end content_doc.comment||='Document activated' }} aasm_state :rejected, {:enter=>Proc.new { |obj| obj.comment||='Document rejected'}} aasm_state :historical, {:enter=>Proc.new { |obj| obj.comment='Document shelved'}} aasm_event :activate_content, :success => :activation_success do transitions :from => [:historical, :pending_review, :new, :rejected, :quarantined, :active], :to => :active, :guard =>"activateable?" end aasm_event :reject_content, :success => :rejection_success do transitions :from => [:pending_review, :active, :quarantined], :to => :rejected end aasm_event :shelve_content do transitions :from => [:rejected, :pending_review, :active, :quarantined], :to => :historical end aasm_event :stage_content, :success => :copy_state_forward do transitions :from => [:quarantined], :to => :pending_review end aasm_event :quarantine_content, :success => :quarantine_success do transitions :from => [:new], :to => :quarantined end def filtered_words self.content_fields.inject([]){|acc, cf| acc + cf.filtered_words} end def activation_success copy_all_fields_forward old_copies = ContentDocument.find :all, :conditions => "owner_id = #{owner_id} AND owner_type = '#{owner_type}' AND status != 'historical' AND id != #{id}" old_copies.each{ |e| e.shelve_content! } owner.save owner.after_activation[self] end def quarantine_success o = owner.reload unless o.content_documents.size > 1 o.update_attribute(o.state_field, status) end o.after_quarantine[self] end def rejection_success activation_success owner.after_rejection[self] end def copy_all_fields_forward owner=self.owner.reload owner.write_attribute(owner.state_field, self.status) content_fields.each{ |f| write_content_field(f) } owner end def copy_content_fields_forward content_fields.each{ |f| write_content_field(f) } owner end def copy_state_forward unless owner.content_documents.size > 1 owner.write_attribute(owner.state_field, status) owner.save! # owner.update_attribute(owner.state_field, status) end owner end def rejection_requires_code errors.add_to_base("Documents marked for rejection require a reason code to be set.") if status == 'rejected' && YAML::load(reason_codes || nil.to_yaml).nil? end def codes_requires_rejection errors.add_to_base("Documents with reason codes must be rejected") if status != 'rejected' && !YAML::load(reason_codes || nil.to_yaml).nil? end def status_with_cascade_override return overriden_cascade? ? cascaded_state_field_value : status end def overriden_cascade? ['rejected', 'historical'].include?(cascaded_state_field_value) if self.owner.respond_to?(cascaded_state_field_name) end private def write_content_field(f) if owner.class.reflect_on_association(f.field_name.try(:to_sym)) if f.field_value.is_a?(Hash) && f.field_value[:class_name] field_value = f.field_value[:class_name].constantize.find(:all, :conditions => ["id in (?)", f.field_value[:ids]]) else field_value = f.field_value end begin owner.send("#{f.field_name}=", field_value) rescue ActiveRecord::AssociationTypeMismatch logger.error("!!! ContentField #{f.id} produced unexpected data") end else field_value = f.field_value f.filtered_words.each{|w| field_value[w.offset,w.length] = '*' * w.length if w.status=='banned'} owner.write_attribute(f.field_name, field_value) end end def journal_state last_content_history = self.content_histories.last if last_content_history.nil? || !(last_content_history.status == self.status && last_content_history.comment == self.comment && last_content_history.reason_codes == self.reason_codes) ContentHistory.create!(:content_document_id => self.id, :status=>self.status, :user_id=>self.user_id, :comment=>self.comment, :reason_codes=>self.reason_codes ) end end def activateable? self.owner.activateable[self] end def cascaded_state_field_name self.owner.class.cascaded_state_field_name end def cascaded_state_field_value self.owner.send(cascaded_state_field_name) end end
module Typhoid module Multi def remote_resources(hydra = nil) request_queue = RequestQueue.new(self, hydra) yield request_queue if block_given? request_queue.run request_queue.requests.each do |req| parse_queued_response req end end protected def parse_queued_response(req) varname = "@" + req.name.to_s req.target.instance_variable_set varname.to_sym, Typhoid::Resource.build(req.klass, req.response) end end end
class CreateYears < ActiveRecord::Migration def change create_table :years do |t| t.integer :anio t.timestamps null: false end end end
module Gnews class Client attr_reader :response RequestError = Class.new(RuntimeError) ConfigError = Class.new(RuntimeError) def call(q:, lang: 'en') raise ConfigError, 'Missing ENV[GNEWS_SEARCH_URL]' unless config[:GNEWS_SEARCH_URL] begin url = build_query_from(q, lang) raw_response = get(url) @response = success?(raw_response) ? parse(raw_response) : {} rescue => e raise RequestError, "Get Request: #{e.message}" end end private delegate :get, to:'::RestClient' def success?(raw_response) raw_response.code == 200 end def parse(raw_response) JSON.parse(raw_response.body) end def build_query_from(q, lang) query = config[:GNEWS_SEARCH_URL] query << "?q=#{q}" query << "&token=#{config[:GNEWS_TOKEN]}" query << "&lang=#{lang}" end def config Rails.application.credentials.config end end end
# -*- mode: ruby -*- # vi: set ft=ruby : require 'securerandom' random_string1 = SecureRandom.hex random_string2 = SecureRandom.hex cluster_init_token = "#{random_string1[0..5]}.#{random_string2[0..15]}" NUM_NODES = 2 NODE_MEM = '4096' Vagrant.configure('2') do |config| (1..NUM_NODES).each do |node_number| node_name = "yolean-k8s-#{node_number}" config.vm.define node_name do |node| node.vm.box = "centos/7" node.vm.box_version = "1706.02" node.vm.box_check_update = false node.vm.hostname = "#{node_name}" node_address = 10 + node_number node_ip = "192.168.38.#{node_address}" node.vm.network 'private_network', ip: "#{node_ip}" node.vm.provider 'virtualbox' do |vb| vb.memory = NODE_MEM end # required by kubeadm, needed at every start node.vm.provision "shell", inline: "swapoff -a", run: "always" node.vm.provision 'shell' do |s| s.args = [node_ip, cluster_init_token] s.path = 'setup.sh' end end end end
#!/usr/bin/env ruby # http://projecteuler.net/problem=5 # Least Common Multiple def lcm(*numbers) numbers = numbers.clone result = 1 divisor = 2 until numbers.empty? while numbers.any? { |n| n % divisor == 0 } result *= divisor numbers.map! { |n| if n % divisor == 0 then (n / divisor) else n end } end numbers.delete_if { |n| n == 1 } divisor += 1 end result end puts lcm(*1..20)
class CreateTexts < ActiveRecord::Migration def change create_table :texts do |t| t.text :text t.string :lang t.references :item, :polymorphic => {:default => 'User'} t.timestamps end end end
require 'singleton' module Pdns # Domains for reverse DNS domains = Pdns.config.get_module_config('reverse')['domains'].split(',') # Subnets subnets = Pdns.config.get_module_config('reverse')['subnets'].split(',') default_domain = Pdns.config.get_module_config('reverse')['default_domain'] refresh_time = (Pdns.config.get_module_config('reverse')['refresh_time'].to_s or 60) class ReverseDatabase include Singleton def initialize @database = nil if Pdns.config.get_module_config('reverse')['database'] @database_path = Pdns.config.get_module_config('reverse')['database'] else @database_path = '/etc/pdns/reverse-database.txt' end @content = nil @last_update = nil end def content unless @content @entries = Hash.new File.foreach(@database_path) do |line| line.strip! # Skip comments next if line[0..0] == '#' row = line.split(',') row[0].strip! if row[0] and row[0].match(/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) and row[1] # Valid entry @entries[row[0]] = row[1].strip end end @last_update = Time.now end @entries end def self.get_reverse_from_ip address self.instance.content[address] end def self.get_ip_from_reverse reverse result = self.instance.content.find{ |e| e[1] == reverse.downcase } return result[0] if result and result[0] end end # Private methods # We register for the subdomain domains.each do |domain| regexp = Regexp.new(".+\.#{domain.gsub('.','\\.')}") newrecord(regexp) do |query, answer| # Answer only if request is A or ANY if query[:qclass] == :IN and (query[:qtype] == :ANY or query[:qtype] == :PTR) # The return type is always A answer.qtype :A # Look if the query is a valid reverse from our database if(address = ReverseDatabase.get_ip_from_reverse(query[:qname])) answer.content address else # Try to find the IP from the query, if this is the default domain if domain == default_domain reverse = query[:qname] match = reverse.match(Regexp.new('([0-9]+-[0-9]+-[0-9]+-[0-9]+)\\.'+domain.gsub('.','\\.'))) if match and match[1] address = match[1].gsub('-', '.') answer.content address end end end end end end # We register for the IP ranges subnets.each do |subnet| delegated_zone = subnet.split('.').reverse.join('.')+'.in-addr.arpa' regexp = Regexp.new(".+\\.#{delegated_zone.gsub('.','\\.')}") newrecord(regexp) do |query, answer| result = query[:qname].match(/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\.in-addr\.arpa/) if query[:qclass] == :IN and (query[:qtype] == :ANY or query[:qtype] == :PTR) and result and result[1] # Get the queried IP address from the request address = result[1].split('.').reverse.join('.') # Set the PTR type answer answer.qtype :PTR # Look if the IP has a custom reverse DNS if(reverse = ReverseDatabase.get_reverse_from_ip(address)) answer.content(reverse) else # Default reverse answer.content(address.gsub('.', '-')+'.'+default_domain) end end end # We need to anwser NS queries for delegated zone newrecord(delegated_zone) do |query,answer| Pdns.error(query) if query[:qclass] == :IN and (query[:qtype] == :NS or query[:qtype] == :ANY) answer.qtype :NS answer.content 'ns3.fotolia.net' answer.content 'ns4.fotolia.net' end end end end # vi:tabstop=2:expandtab:ai:filetype=ruby:sw=2:softtabstop=2
class CreateAnimees < ActiveRecord::Migration def change create_table :animees do |t| t.string :name t.timestamps end end end
class User < ActiveRecord::Base devise :database_authenticatable, :recoverable, :rememberable, :trackable, :registerable attr_accessible :email, :password, :password_confirmation, :remember_me has_many :games def self.current Thread.current[:user] end def self.current=(user) Thread.current[:user] = user end end
Rails.application.routes.draw do get '/home', to: 'static_pages#home' get '/contact', to: 'static_pages#contact' get '/sponsors', to: 'static_pages#sponsors' # get '/altronics' load: 'app/assests/images/altronics.png' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html #match 'static_pages/contact' => 'static_pages#contact' root 'static_pages#home' end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'archivalSort', type: :system, clean: true do before do solr = Blacklight.default_index.connection solr.add([dog, cat, llama, eagle, puppy]) solr.commit visit '/catalog?per_page=1&q=&search_field=all_fields' end let(:dog) do { id: '111', title_tesim: ['Amor Perro'], creator_tesim: 'Me and You', creator_ssim: ['Me and You'], year_isim: [1999], resourceType_ssim: 'Archives or Manuscripts', callNumber_tesim: 'Beinecke MS 801', imageCount_isi: '23', visibility_ssi: 'Public', archivalSort_ssi: '08001.00038', ancestorTitles_tesim: ['Beinecke Rare Book and Manuscript Library (BRBL)', 'Osborn Manuscript Files (OSB MSS FILE)', 'Numerical Sequence: 17975-19123', 'BURNEY, SARAH HARRIET, 1772-1844', 'Level3', 'Level2', 'Level1', 'Level0'] } end let(:cat) do { id: '222', title_tesim: ['Amor Gato'], creator_tesim: 'Me and You', creator_ssim: ['Me and You'], year_isim: [1999], resourceType_ssim: 'Archives or Manuscripts', callNumber_tesim: 'Beinecke MS 801', imageCount_isi: '23', visibility_ssi: 'Public', archivalSort_ssi: '00006.00040', ancestorTitles_tesim: ['Beinecke Rare Book and Manuscript Library (BRBL)', 'Script Files', 'Numerical Sequence: 17975-19123', 'BURNEY, SARAH HARRIET, 1772-1844', 'Level3', 'Level2', 'Level1', 'Level0'] } end let(:llama) do { id: '333', title_tesim: ['Amor Llama'], creator_tesim: 'Anna Elizabeth Dewdney', creator_ssim: ['Anna Elizabeth Dewdney'], year_isim: [1999], repository_ssi: 'Yale University Arts Library', collection_title_ssi: ['AAA'], format: 'text', language_ssim: 'la', visibility_ssi: 'Public', genre_ssim: 'Maps', resourceType_ssim: 'Maps, Atlases & Globes', archivalSort_ssi: '00000.00040', ancestorTitles_tesim: ['Beinecke Rare Book and Manuscript Library (BRBL)', 'Llama Files', 'Numerical Sequence: 17975-19123', 'BURNEY, SARAH HARRIET, 1772-1844', 'Level3', 'Level2', 'Level1', 'Level0'] } end let(:eagle) do { id: '444', title_tesim: ['Aquila Eccellenza'], creator_tesim: 'Andrew Norriss', creator_ssim: ['Andrew Norriss'], year_isim: [1999], format: 'still image', language_ssim: 'it', visibility_ssi: 'Public', genre_ssim: 'Manuscripts', resourceType_ssim: 'Archives or Manuscripts', archivalSort_ssi: '00020.00040', ancestorTitles_tesim: ['Beinecke Rare Book and Manuscript Library (BRBL)', 'Eagle Files', 'Numerical Sequence: 17975-19123', 'BURNEY, SARAH HARRIET, 1772-1844', 'Level3', 'Level2', 'Level1', 'Level0'] } end let(:puppy) do { id: '555', title_tesim: ['Rhett Lecheire'], creator_tesim: 'Paulo Coelho', creator_ssim: ['Paulo Coelho'], year_isim: [1999], format: 'text', language_ssim: 'fr', visibility_ssi: 'Public', genre_ssim: 'Animation', resourceType_ssim: 'Archives or Manuscripts', archivalSort_ssi: '04000.00040', ancestorTitles_tesim: ['Beinecke Rare Book and Manuscript Library (BRBL)', 'Puppy Files', 'Numerical Sequence: 17975-19123', 'BURNEY, SARAH HARRIET, 1772-1844', 'Level3', 'Level2', 'Level1', 'Level0'] } end context 'search results' do it 'sorts based on archivalSort conditions' do expect(page).to have_content('Llama Files') expect(page).not_to have_content('Script Files') end end end
# require 'yaml_db' require_relative 'demo/tasks' require_relative 'demo/setup' require_relative 'demo/utils' require_relative 'demo/db' def demo_branch fetch(:demo_branch, `git rev-parse --abbrev-ref HEAD`.strip).downcase end def demo_host fetch(:demo_host) end def demo_url format("%s.%s", demo_branch, demo_host) end def demo_path deploy_path.join('demo', demo_branch) end def demo_default_db format("%s_%s", fetch(:application), fetch(:stage)) end
class RenameColumnAuthId < ActiveRecord::Migration[5.2] def change rename_column :books, :auth_id, :author_id end end
RSpec.feature "BEIS users can download exports" do let(:beis_user) { create(:beis_user) } before do Fund.all.each { |fund| create(:fund_activity, source_fund_code: fund.id, roda_identifier: fund.short_name) } authenticate! user: beis_user end after { logout } scenario "downloading the actuals for a partner organisation" do partner_organisation = create(:partner_organisation) project = create(:project_activity, organisation: partner_organisation) create(:actual, parent_activity: project, financial_year: 2019, financial_quarter: 3, value: 150) visit exports_path click_link partner_organisation.name click_link "Download All actuals" document = CSV.parse(page.body.delete_prefix("\uFEFF"), headers: true).map(&:to_h) expect(document).to match_array([ { "Activity RODA Identifier" => project.roda_identifier, "Activity BEIS Identifier" => project.beis_identifier, "FQ3 2019-2020" => "150.00" } ]) end scenario "downloading the external income for a partner organisation" do partner_organisation = create(:partner_organisation) project = create(:project_activity, :newton_funded, organisation: partner_organisation) ext_income1 = create(:external_income, activity: project, financial_year: 2019, financial_quarter: 3, amount: 120) ext_income2 = create(:external_income, activity: project, financial_year: 2021, financial_quarter: 1, amount: 240) visit exports_path click_link partner_organisation.name click_link "Newton Fund external income" document = CSV.parse(page.body.delete_prefix("\uFEFF"), headers: true).map(&:to_h) expect(document.size).to eq(2) expect(document).to match_array([ { "RODA identifier" => project.roda_identifier, "Partner organisation identifier" => project.partner_organisation_identifier, "Partner organisation" => partner_organisation.name, "Title" => project.title, "Level" => "Project (level C)", "Providing organisation" => ext_income1.organisation.name, "ODA" => "Yes", "FQ3 2019-2020" => "120.00", "FQ4 2019-2020" => "0.00", "FQ1 2020-2021" => "0.00", "FQ2 2020-2021" => "0.00", "FQ3 2020-2021" => "0.00", "FQ4 2020-2021" => "0.00", "FQ1 2021-2022" => "0.00" }, { "RODA identifier" => project.roda_identifier, "Partner organisation identifier" => project.partner_organisation_identifier, "Partner organisation" => partner_organisation.name, "Title" => project.title, "Level" => "Project (level C)", "Providing organisation" => ext_income2.organisation.name, "ODA" => "Yes", "FQ3 2019-2020" => "0.00", "FQ4 2019-2020" => "0.00", "FQ1 2020-2021" => "0.00", "FQ2 2020-2021" => "0.00", "FQ3 2020-2021" => "0.00", "FQ4 2020-2021" => "0.00", "FQ1 2021-2022" => "240.00" } ]) end scenario "downloading the external income for all partner organisations" do partner_organisation1, partner_organisation2 = create_list(:partner_organisation, 2) project1 = create(:project_activity, :newton_funded, organisation: partner_organisation1) project2 = create(:project_activity, :newton_funded, organisation: partner_organisation2) ext_income1 = create(:external_income, activity: project1, financial_year: 2019, financial_quarter: 3, amount: 120) ext_income2 = create(:external_income, activity: project2, financial_year: 2021, financial_quarter: 1, amount: 240) ext_income3 = create(:external_income, activity: project2, financial_year: 2021, financial_quarter: 2, amount: 100) visit exports_path click_link "Download External income for Newton Fund" document = CSV.parse(page.body.delete_prefix("\uFEFF"), headers: true).map(&:to_h) expect(document.size).to eq(3) expect(document).to match_array([ { "RODA identifier" => project1.roda_identifier, "Partner organisation identifier" => project1.partner_organisation_identifier, "Partner organisation" => partner_organisation1.name, "Title" => project1.title, "Level" => "Project (level C)", "Providing organisation" => ext_income1.organisation.name, "ODA" => "Yes", "FQ3 2019-2020" => "120.00", "FQ4 2019-2020" => "0.00", "FQ1 2020-2021" => "0.00", "FQ2 2020-2021" => "0.00", "FQ3 2020-2021" => "0.00", "FQ4 2020-2021" => "0.00", "FQ1 2021-2022" => "0.00", "FQ2 2021-2022" => "0.00" }, { "RODA identifier" => project2.roda_identifier, "Partner organisation identifier" => project2.partner_organisation_identifier, "Partner organisation" => partner_organisation2.name, "Title" => project2.title, "Level" => "Project (level C)", "Providing organisation" => ext_income2.organisation.name, "ODA" => "Yes", "FQ3 2019-2020" => "0.00", "FQ4 2019-2020" => "0.00", "FQ1 2020-2021" => "0.00", "FQ2 2020-2021" => "0.00", "FQ3 2020-2021" => "0.00", "FQ4 2020-2021" => "0.00", "FQ1 2021-2022" => "240.00", "FQ2 2021-2022" => "0.00" }, { "RODA identifier" => project2.roda_identifier, "Partner organisation identifier" => project2.partner_organisation_identifier, "Partner organisation" => partner_organisation2.name, "Title" => project2.title, "Level" => "Project (level C)", "Providing organisation" => ext_income3.organisation.name, "ODA" => "Yes", "FQ3 2019-2020" => "0.00", "FQ4 2019-2020" => "0.00", "FQ1 2020-2021" => "0.00", "FQ2 2020-2021" => "0.00", "FQ3 2020-2021" => "0.00", "FQ4 2020-2021" => "0.00", "FQ1 2021-2022" => "0.00", "FQ2 2021-2022" => "100.00" } ]) end scenario "downloading budgets for a partner organisation" do partner_organisation = create(:partner_organisation) report = create(:report) programme = create(:programme_activity, extending_organisation: partner_organisation) project = create(:project_activity, :newton_funded, extending_organisation: partner_organisation) create(:budget, financial_year: 2021, value: 1000, parent_activity: programme, report: nil) create(:budget, financial_year: 2018, value: 100, parent_activity: project, report: report) create(:budget, financial_year: 2019, value: 80, parent_activity: project, report: report) create(:budget, financial_year: 2020, value: 75, parent_activity: project, report: report) create(:budget, financial_year: 2021, value: 20, parent_activity: project, report: report) programme_comment = create(:comment, commentable: programme, owner: beis_user, body: "I am a programme comment") visit exports_path click_link partner_organisation.name click_link "Newton Fund budgets" document = CSV.parse(page.body.delete_prefix("\uFEFF"), headers: true).map(&:to_h) expect(document.size).to eq(2) expect(document).to match_array([ { "RODA identifier" => programme.roda_identifier, "Partner organisation identifier" => programme.partner_organisation_identifier, "Partner organisation" => programme.extending_organisation.name, "Level" => "Programme (level B)", "Title" => programme.title, "Level B activity comments" => programme_comment.body, "2018-2019" => "0.00", "2019-2020" => "0.00", "2020-2021" => "0.00", "2021-2022" => "1000.00" }, { "RODA identifier" => project.roda_identifier, "Partner organisation identifier" => project.partner_organisation_identifier, "Partner organisation" => partner_organisation.name, "Level" => "Project (level C)", "Title" => project.title, "Level B activity comments" => "", "2018-2019" => "100.00", "2019-2020" => "80.00", "2020-2021" => "75.00", "2021-2022" => "20.00" } ]) end scenario "downloading budgets for all partner organisations" do partner_organisation1, partner_organisation2 = create_list(:partner_organisation, 2) report = create(:report) programme = create(:programme_activity) project1 = create(:project_activity, :newton_funded, extending_organisation: partner_organisation1, parent: programme) project2 = create(:project_activity, :newton_funded, extending_organisation: partner_organisation2, parent: programme) create(:budget, financial_year: 2021, value: 1000, parent_activity: programme, report: nil) create(:budget, financial_year: 2018, value: 100, parent_activity: project1, report: report) create(:budget, financial_year: 2019, value: 80, parent_activity: project1, report: report) create(:budget, financial_year: 2021, value: 20, parent_activity: project1, report: report) create(:budget, financial_year: 2018, value: 100, parent_activity: project2, report: report) create(:budget, financial_year: 2019, value: 80, parent_activity: project2, report: report) create(:budget, financial_year: 2020, value: 75, parent_activity: project2, report: report) create(:budget, financial_year: 2021, value: 20, parent_activity: project2, report: report) create(:budget, financial_year: 2021, value: 60, parent_activity: project2, report: report) programme_comment_1 = create(:comment, commentable: programme, owner: beis_user, body: "I like big budgets and I cannot lie") programme_comment_2 = create(:comment, commentable: programme, owner: beis_user, body: "The chief budgerigar asked if we could budge over this budget") visit exports_path click_link "Download Budgets for Newton Fund" document = CSV.parse(page.body.delete_prefix("\uFEFF"), headers: true).map(&:to_h) expect(document.size).to eq(4) expect(document).to match_array([ { "RODA identifier" => programme.roda_identifier, "Partner organisation identifier" => programme.partner_organisation_identifier, "Partner organisation" => programme.extending_organisation.name, "Level" => "Programme (level B)", "Title" => programme.title, "Level B activity comments" => [programme_comment_1, programme_comment_2].map(&:body).join("|"), "2018-2019" => "0.00", "2019-2020" => "0.00", "2020-2021" => "0.00", "2021-2022" => "1000.00" }, { "RODA identifier" => project1.roda_identifier, "Partner organisation identifier" => project1.partner_organisation_identifier, "Partner organisation" => partner_organisation1.name, "Level" => "Project (level C)", "Title" => project1.title, "Level B activity comments" => "", "2018-2019" => "100.00", "2019-2020" => "80.00", "2020-2021" => "0.00", "2021-2022" => "20.00" }, { "RODA identifier" => project2.roda_identifier, "Partner organisation identifier" => project2.partner_organisation_identifier, "Partner organisation" => partner_organisation2.name, "Level" => "Project (level C)", "Title" => project2.title, "Level B activity comments" => "", "2018-2019" => "100.00", "2019-2020" => "80.00", "2020-2021" => "75.00", "2021-2022" => "20.00" }, { "RODA identifier" => project2.roda_identifier, "Partner organisation identifier" => project2.partner_organisation_identifier, "Partner organisation" => partner_organisation2.name, "Level" => "Project (level C)", "Title" => project2.title, "Level B activity comments" => "", "2018-2019" => "0.00", "2019-2020" => "0.00", "2020-2021" => "0.00", "2021-2022" => "60.00" } ]) end scenario "downloading IATI exports for a partner organisation" do organisation = create(:partner_organisation) publishable_activity = create(:programme_activity, :gcrf_funded, extending_organisation: organisation, publish_to_iati: true) unpublishable_activity = create(:programme_activity, :newton_funded, extending_organisation: organisation, publish_to_iati: false) visit exports_organisation_path(organisation) expect(page).to have_content("#{publishable_activity.source_fund.name} IATI export for programme (level B) activities") expect(page).not_to have_content("#{unpublishable_activity.source_fund.name} IATI export for programme (level B) activities") end end
require 'rails_helper' RSpec.feature 'User sees tags on jobs page' do scenario 'a user can see appropriate tags on jobs page' do company = Company.create!(name: "ESPN") job = company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver") tag_1 = job.tags.create!(name:'Software') tag_2 = job.tags.create!(name:'Good-Location') visit company_job_path(company, job) expect(page).to have_content("ESPN") expect(page).to have_content("Developer") expect(page).to have_content("70") expect(page).to have_content(tag_1.name) expect(page).to have_content(tag_2.name) end scenario 'a user can see how many jobs each tag has' do company = Company.create!(name: "ESPN") job = company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver") job_2 = company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver") job_3 = company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver") job_4 = company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver") tag_1 = job.tags.create!(name:'Software') tag_2 = job.tags.create!(name:'Good-Location') job_2.tags << tag_1 job_3.tags << tag_1 job_4.tags << tag_1 job_4.tags << tag_2 visit company_job_path(company, job) expect(page).to have_content("ESPN") expect(page).to have_content("Developer") expect(page).to have_content("70") expect(page).to have_content("#{tag_1.name} - #{tag_1.job_count}") expect(page).to have_content("#{tag_2.name} - #{tag_2.job_count}") end end
module PostsHelper def post_path(post) blog_path(post) end def cache_key_for_posts count = Post.count max_updated_at = Post.maximum(:updated_at).try(:utc).try(:to_s, :number) "posts/all-#{count}-#{max_updated_at}" end end
require 'spec_helper' describe MoneyMover::Dwolla::CustomerFundingSourceResource do let(:customer_id) { 123987 } let(:funding_source_id) { 777 } it_behaves_like 'base resource list' do let(:id) { customer_id } let(:expected_path) { "/customers/#{id}/funding-sources" } let(:valid_filter_params) { [:removed] } end it_behaves_like 'base resource find' do let(:id) { funding_source_id } let(:expected_path) { "/funding-sources/#{id}" } end it_behaves_like 'base resource create' do let(:id) { customer_id } let(:expected_path) { "/customers/#{id}/funding-sources" } end it_behaves_like 'base resource update' do let(:id) { funding_source_id } let(:expected_config_path) { '/funding-sources/:id' } let(:expected_path) { "/funding-sources/#{id}" } end it_behaves_like 'base resource destroy' do let(:id) { funding_source_id } let(:expected_config_path) { '/funding-sources/:id' } let(:expected_path) { "/funding-sources/#{id}" } end end
class EmployeeSkillsController < ApplicationController # GET /employee_skills # GET /employee_skills.json def index @employee_skills = EmployeeSkill.all respond_to do |format| format.html # index.html.erb format.json { render json: @employee_skills } end end # GET /employee_skills/1 # GET /employee_skills/1.json def show @employee_skill = EmployeeSkill.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @employee_skill } end end # GET /employee_skills/new # GET /employee_skills/new.json def new @employee_skill = EmployeeSkill.new respond_to do |format| format.html # new.html.erb format.json { render json: @employee_skill } end end # GET /employee_skills/1/edit def edit @employee_skill = EmployeeSkill.find(params[:id]) end # POST /employee_skills # POST /employee_skills.json def create @employee_skill = EmployeeSkill.new(params[:employee_skill]) respond_to do |format| if @employee_skill.save format.html { redirect_to @employee_skill, notice: 'Employee skill was successfully created.' } format.json { render json: @employee_skill, status: :created, location: @employee_skill } else format.html { render action: "new" } format.json { render json: @employee_skill.errors, status: :unprocessable_entity } end end end # PUT /employee_skills/1 # PUT /employee_skills/1.json def update @employee_skill = EmployeeSkill.find(params[:id]) respond_to do |format| if @employee_skill.update_attributes(params[:employee_skill]) format.html { redirect_to @employee_skill, notice: 'Employee skill was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @employee_skill.errors, status: :unprocessable_entity } end end end # DELETE /employee_skills/1 # DELETE /employee_skills/1.json def destroy @employee_skill = EmployeeSkill.find(params[:id]) @employee_skill.destroy respond_to do |format| format.html { redirect_to employee_skills_url } format.json { head :no_content } end end end
Decanter.config do |config| # Possible values are :with_exception, true or false config.strict = :with_exception end
remote_cache = lambda do cache = fetch(:remote_cache) cache = deploy_to + "/" + cache if cache && cache !~ /^\// cache end namespace :load do task :defaults do set :rsync_exclude, %w[.git*] set :rsync_include, %w[ ] set :rsync_options, %w[--archive --recursive --delete --delete-excluded] set :copy_command, "rsync --archive --acls --xattrs" set :local_cache, ".rsync_#{fetch(:stage)}" set :remote_cache, "shared/rsync" set :repo_url, File.expand_path(".") end end namespace "rsync" do task :check do # nothing to check, but expected by framework end task :create_cache do next if File.directory?(File.expand_path(fetch(:local_cache))) # TODO: check if it's actually our repo instead of assuming run_locally do execute :git, 'clone', fetch(:repo_url), fetch(:local_cache) end end desc "stage the repository in a local directory" task :stage => [ :create_cache ] do run_locally do within fetch(:local_cache) do execute :git, "fetch", "--quiet", "--all", "--prune" execute :git, "reset", "--hard", "origin/#{fetch(:branch)}" end end end desc "stage and rsync to the server" task :sync => [ :stage ] do release_roles(:all).each do |role| user = role.user || fetch(:user) user = user + "@" unless user.nil? rsync_args = [] rsync_args.concat fetch(:rsync_options) rsync_args.concat fetch(:rsync_include, []).map{|e| "--include #{e}"} rsync_args.concat fetch(:rsync_exclude, []).map{|e| "--exclude #{e}"} rsync_args << fetch(:local_cache) + "/" rsync_args << "#{user}#{role.hostname}:#{remote_cache.call}" run_locally do execute :rsync, *rsync_args end end end desc "stage, rsync to the server, and copy the code to the releases directory" task :release => [ :sync ] do copy = %(#{fetch(:copy_command)} "#{remote_cache.call}/" "#{release_path}/") on release_roles(:all) do execute copy end end task :create_release => [ :release ] do # expected by the framework, delegate to better named task end task :set_current_revision do run_locally do set :current_revision, capture(:git, 'rev-parse', fetch(:branch)) end end end
# EventHub module module EventHub def self.logger unless defined?(@logger) @logger = ::EventHub::Components::MultiLogger.new @logger.add_device(Logger.new($stdout)) @logger.add_device( EventHub::Components::Logger.logstash(Configuration.name, Configuration.environment) ) end @logger end end
# Pick out the minimum age from our current Munster family hash: ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } ages.values.min # => 10 # #values returns an array of all values from the hash. # Enumerable#min can be used on an array or hash. It is called on teh return value of #values to give the object with the mininmum value.
require_relative "lib/poker_round" class PokerGame attr_accessor :file_name, :player_1_score def initialize(file_name) @player_1_score = 0 @file_name = file_name end def play_game File.readlines(file_name).each do |line| result = PokerRound.new(line).play_hand if result == "Player 1 wins" @player_1_score += 1 end end puts "Player 1 wins #{@player_1_score} hands" end end
class Users::RegistrationsController < Devise::RegistrationsController # before_filter :configure_sign_up_params, only: [:create] # before_filter :configure_account_update_params, only: [:update] before_filter :verify_is_admin, only: [:admin_edit,:admin_update] # GET /resource/sign_up # def new # super # end # POST /resource def create build_resource(sign_up_params) resource_saved = resource.save yield resource if block_given? if resource_saved if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_flashing_format? sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format? expire_data_after_sign_in! redirect_to :new_user_session, flash: {notice: "Seu registro foi efetuado com sucesso! Por favor aguarde a aprovação do admnistrador!"} end else clean_up_passwords resource @validatable = devise_mapping.validatable? if @validatable @minimum_password_length = resource_class.password_length.min end respond_with resource end # redirect_to :back, flash: {error: "Oops, something went wrong. Please try again"} end # GET /resource/edit # def edit # @user = User.find(params[:id]) # end # PUT /resource #def update # super #end def admin_edit @user = User.find(params[:id]) end def admin_update if current_user.admin? respond_to do |format| @user = User.find(params[:id]) if @user.update(account_update_params) format.html { redirect_to user_index_path, notice: 'Usuário editado com sucesso!' } format.json { render :show, status: :ok, location: @user } else format.html { render :admin_edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end end # DELETE /resource def destroy super @user = User.find(params[:id]) @user.destroy end # GET /resource/cancel # Forces the session data which is usually expired after sign # in to be expired now. This is useful if the user wants to # cancel oauth signing in/up in the middle of the process, # removing all OAuth session data. # def cancel # super # end # protected # You can put the params you want to permit in the empty array. # def configure_sign_up_params # devise_parameter_sanitizer.for(:sign_up) << :name # end # def configure_permitted_parameters # devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :ra, :role, :type, :internal, :institution, :email, :password, :password_confirmation, :remember_me) } # devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:name, :ra, :role, :type, :internal, :institution, :email, :password, :password_confirmation, :remember_me) } # end # You can put the params you want to permit in the empty array. # def configure_account_update_params # devise_parameter_sanitizer.for(:account_update) << :attribute # end # The path used after sign up. # def after_sign_up_path_for(resource) # super(resource) # end # The path used after sign up for inactive accounts. # def after_inactive_sign_up_path_for(resource) # super(resource) # end private def verify_is_admin (current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?) end protected def after_update_path_for(resource) case resource when :user, User root_path else super end end def after_update_path_for(resource) root_path end def after_put_path_for(resource) root_path end def after_patch_path_for(resource) case resource when :user, User root_path else super end end def account_update_params params.require(:user).permit(:name, :ra, :role, :type, :internal, :institution, :email, :password, :password_confirmation, :current_password) end end
class User < ApplicationRecord authenticates_with_sorcery! has_many :decks has_many :cards validates_confirmation_of :password validates :password, presence: true, on: :create validates :email, presence: true, uniqueness: true def current_deck decks.where(current: true).first end end
class WidgetList::VideoListWidget < AuthorizableWidget responds_to_event :delete_widget, :with => :destroy def display @video_list = options[:widget] render end def destroy(evt) section = VideoList.find(evt[:widget_id]).section VideoList.find(evt[:widget_id]).destroy trigger :widgetDeleted, :section => section end end
# ../data.img#1772233:1 require_relative '../../lib/dom/dom' require_relative '../../lib/code_object/base' describe Dom::Node, "#resolve" do before do Dom.clear @o1 = CodeObject::Base.new @o2 = CodeObject::Base.new @o3 = CodeObject::Base.new @o4 = CodeObject::Base.new Dom.add_node "Foo.bar" , @o1 @o1.add_node ".baz" , @o2 @o1.add_node ".baz.bam", @o3 @o1.add_node ".baz.poo", @o4 end it "should find existing node in domtree" do @o4.resolve('.bar').should == @o1 @o4.resolve('.baz').should == @o2 @o4.resolve('.bam').should == @o3 @o4.resolve('.poo').should == @o4 end it "should not find non existing nodes" do @o1.resolve('fofofo').should == nil end end describe Dom::Node, "#qualified_name" do before do Dom.clear @o1 = CodeObject::Base.new "bar" @o2 = CodeObject::Base.new "baz" @o3 = CodeObject::Base.new "bam" @o4 = CodeObject::Base.new "poo" Dom.add_node "Foo.bar" , @o1 @o1.add_node ".baz" , @o2 @o1.add_node ".baz.bam", @o3 @o1.add_node ".baz.poo", @o4 end it "should generate correct qualified name from structure" do @o1.qualified_name.should == "Foo.bar" @o2.qualified_name.should == "Foo.bar.baz" @o3.qualified_name.should == "Foo.bar.baz.bam" @o4.qualified_name.should == "Foo.bar.baz.poo" end end
class ApplicationMailer < ActionMailer::Base default from: ENV['MAILER_FROM'] || 'info@makeitreal.camp' layout 'mailer' helper ApplicationHelper def genderize(male, female, user=current_user) user.gender == "female" ? female : male end end
class MakeInvLinesDefault < ActiveRecord::Migration[6.0] def change InventoryLine.where(quantity_present: nil).update_all(quantity_present: 0) InventoryLine.where(quantity_desired: nil).update_all(quantity_desired: 0) change_column_default(:inventory_lines, :quantity_present, from: nil, to: 0) change_column_default(:inventory_lines, :quantity_desired, from: nil, to: 0) change_column_null(:inventory_lines, :quantity_desired, false) change_column_null(:inventory_lines, :quantity_present, false) end end
class Api::V1::RevenueController < ApplicationController def date_range revenue = RevenueFacade.date_range(params[:start], params[:end]) render json: RevenueSerializer.new(revenue) end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'reviews edit process' do # need to test with css tag # it "can take a user to reviews edit page" do # visit("/shelters/#{@shelter1.id}") # # click_link("Edit Review") # # expect(current_path).to eq("/reviews/#{@review1.id}/edit") # end it 'user can see a form to edit review data' do visit("/reviews/#{@review1.id}/edit") expect(page).to have_selector('form') expect(page).to have_field('Title', with: @review1.title) expect(page).to have_field('Content', with: @review1.content) end it 'user can complete edit update with PATCH and redirect' do visit("/reviews/#{@review1.id}/edit") fill_in 'Title', with: 'Update title test' click_button 'Submit' expect(current_path).to eq("/shelters/#{@review1.shelter.id}") expect(page).to have_content('Update title test') expect(page).to_not have_content('This is Awesome') end it 'user can see an error message when the form is not complete (title)' do visit("/reviews/#{@review1.id}/edit") fill_in 'Title', with: '' click_button 'Submit' expect(current_path).to eq("/reviews/#{@review1.id}/edit") expect(page).to have_content('All fields are required') end it 'user can see an error message when the form is not complete (Content)' do visit("/reviews/#{@review1.id}/edit") fill_in 'Content', with: '' click_button 'Submit' expect(current_path).to eq("/reviews/#{@review1.id}/edit") expect(page).to have_content('All fields are required') end end
class ChargesController < ApplicationController def new @order = Order.find_by(id: session[:order]) end def create @order = Order.find_by(id: session[:order]) @amount = @order.stripe_total customer = Stripe::Customer.create( email: current_user.email, card: params[:stripeToken] ) charge = Stripe::Charge.create( customer: customer.id, amount: @amount, description: 'Rails Stripe Customer', currency: 'usd' ) session[:order] = nil @order.update_attributes(pending: false) redirect_to order_path(@order), notice: "Payment of $#{@order.total} accepted" rescue Stripe::CardError => e flash[:error] = e.message end end
class ChangeLocationModel < ActiveRecord::Migration def change remove_column :locations, :state remove_column :locations, :city add_column :locations, :location_name, :string end end
class AddAuthTokenToClients < ActiveRecord::Migration def up add_column :clients, :auth_token, :string, limit: 40 add_index :clients, :auth_token, unique: true Client.all.each do |c| c.update_attribute :auth_token, SecureRandom.uuid.gsub('-', '') end change_column :clients, :auth_token, :string, limit: 40, null: false end def down remove_column :clients, :auth_token end end
cask 'spek' do version '0.8.3' sha256 '648ffe37a4605d76b8d63ca677503ba63338b84c5df73961d9a5335ff144cc54' # github.com/alexkay/spek was verified as official when first introduced to the cask url "https://github.com/alexkay/spek/releases/download/v#{version}/spek-#{version}.dmg" appcast 'https://github.com/alexkay/spek/releases.atom', checkpoint: '2ed5efa777cb07040d9d44e658bec267111b978d4701bbd8d6f6d3e1c1264f49' name 'Spek' homepage 'http://spek.cc/' app 'Spek.app' if MacOS.version >= :high_sierra opoo 'Spek may not work for some users on High Sierra. There are forks with compatibility, but they are not currently available on Homebrew. See https://github.com/caskroom/homebrew-cask/pull/46109 for more information.' end end
# -*- mode: ruby -*- # vi: set ft=ruby : graalvm_version = "19.0.0" graalvm_download_url = "https://github.com/oracle/graal/releases/download/vm-#{graalvm_version}/graalvm-ce-linux-amd64-#{graalvm_version}.tar.gz" Vagrant.configure("2") do |config| config.vm.box = "ubuntu/bionic64" config.vm.provision "shell", inline: <<-SHELL apt-get update apt-get install -y curl if [ ! -d /opt/graalvm-ce ]; then curl -L #{graalvm_download_url} -o graalvm-ce.tar.gz tar -xzvf graalvm-ce.tar.gz -C /opt/ mv /opt/graalvm-ce-19.0.0 /opt/graalvm-ce rm graalvm-ce.tar.gz fi SHELL end
require 'spec_helper' describe "User pages" do subject { page } describe "index" do describe "as a regular user" do let(:user) { FactoryGirl.create(:user) } before(:each) do log_in user visit users_path end it { should have_title('Home') } it { should_not have_headings 'User', 'Overview' } end describe "as an admin user" do let(:admin) { FactoryGirl.create(:admin) } before(:each) do log_in admin visit users_path end it { should have_title('Users') } it { should have_headings 'User', 'Overview' } describe "pagination" do before(:all) { 30.times { FactoryGirl.create(:user) } } after(:all) { User.delete_all } it { should have_selector('div.pagination') } it "should list each user" do User.paginate(page: 1).each do |user| expect(page).to have_selector('li', text: user.name) end end describe "delete links" do it { should_not have_link('delete', href: user_path(admin)) } it { should have_link('delete', href: user_path(User.first)) } it "should be able to delete another user" do expect do click_link('delete', match: :first) end.to change(User, :count).by(-1) end it { should_not have_link('delete', href: user_path(admin)) } end end end end describe "show" do describe "as a regular user" do let(:user) { FactoryGirl.create(:user) } before(:each) do log_in user visit user_path(user) end it { should have_title('Home') } it { should_not have_headings 'User', 'Profile' } end describe "as an admin user" do let(:admin) { FactoryGirl.create(:admin) } let!(:m1) { FactoryGirl.create(:memo, user: admin, name: "A2") } let!(:m2) { FactoryGirl.create(:memo, user: admin, name: "A3") } before(:each) do log_in admin visit user_path(admin) end it { should have_title('Profile') } it { should have_headings 'User', 'Profile' } describe "list of user's memos" do it { should have_content(m1.name) } it { should have_content(m2.name) } it { should have_content(admin.memos.count) } end end end # describe "signup" do # before { visit signup_path } # it { should have_title 'Sign up' } # it { should have_headings 'Account', 'Sign up' } # let(:submit) { "Create my account" } # describe "with invalid information" do # it "should not create a user" do # expect { click_button submit }.not_to change(User, :count) # end # describe "after submission" do # before { click_button submit } # it { should have_error_message 'The form contains' } # end # end # describe "with valid information" do # before { valid_signup } # it "should create a user" do # expect { click_button submit }.to change(User, :count).by(1) # end # describe "after saving the user" do # before { click_button submit } # it { should have_title 'Home' } # it { should have_link 'Log out', href: logout_path } # it { should have_success_message 'Welcome to Scrabble Dojo!' } # end # end # end describe "edit profile" do let(:user) { FactoryGirl.create(:user) } before do log_in user visit edit_user_path(user) end it { should have_title 'Profile' } it { should have_headings 'Account', 'Edit profile' } let(:submit) { "Update my account" } describe "with invalid information" do before { click_button submit } it { should have_error_message 'The form contains' } end describe "with valid information" do let(:new_name) { "New Name" } let(:new_email) { "new@example.com" } before do fill_in "Name", with: new_name fill_in "user_email", with: new_email fill_in "user_password", with: user.password fill_in "user_password_confirmation", with: user.password click_button "Update my account" end it { should have_title 'Home' } it { should have_link 'Log out', href: logout_path } it { should have_success_message 'Profile updated' } specify { expect(user.reload.name).to eq new_name } specify { expect(user.reload.email).to eq new_email } end describe "forbidden attributes" do let(:params) do { user: { admin: true, password: user.password, password_confirmation: user.password } } end before do log_in user, no_capybara: true patch user_path(user), params end specify { expect(user.reload).not_to be_admin } end end end
class Wrap < ApplicationRecord validates :start_time, presence: true, uniqueness: true validates :precaution_title, length: { maximum: 255 } validates :precaution_content, length: { maximum: 255 } validate :date_before_today def date_before_today if start_time.present? && start_time > Date.today errors.add(:date, ": 未来の日付は使用できません") end end belongs_to :pet has_many :conditions, dependent: :destroy, index_errors: true validates_associated :conditions accepts_nested_attributes_for :conditions, allow_destroy: true, reject_if: :all_blank has_many :meals, dependent: :destroy accepts_nested_attributes_for :meals, allow_destroy: true, reject_if: :all_blank has_many :excretions, dependent: :destroy accepts_nested_attributes_for :excretions, allow_destroy: true, reject_if: :all_blank has_many :medicines, dependent: :destroy accepts_nested_attributes_for :medicines, allow_destroy: true, reject_if: :all_blank has_many :walks, dependent: :destroy accepts_nested_attributes_for :walks, allow_destroy: true, reject_if: :all_blank end
get "/students/new" do erb :"students/new" end post "/students" do @student = Student.new(params[:student]) if @student.save redirect "/sessions/new" else @errors = @student.errors.full_messages erb :"students/new" end end get "/students/:id" do if logged_in? @student = Student.find(params[:id]) erb :"students/show" else halt(404, erb(:'404')) end end
require "aws-sdk" module Snapshotar module Storage ## # This snapshot storage type connects to amazon s3 via *aws-sdk gem*. class S3Storage def initialize #:nodoc: raise ArgumentError, "You should set ENV['AWS_ACCESS_KEY_ID'] to a valid value" unless ENV['AWS_ACCESS_KEY_ID'] raise ArgumentError, "You should set ENV['AWS_SECRET_ACCESS_KEY'] to a valid value" unless ENV['AWS_SECRET_ACCESS_KEY'] raise ArgumentError, "You should set ENV['AWS_SNAPSHOTAR_BUCKET'] to a aws bucket name used only for snapshotting" unless ENV['AWS_SNAPSHOTAR_BUCKET'] raise ArgumentError, "You should set ENV['AWS_REGION'] to the region of your s3 bucket" unless ENV['AWS_REGION'] p "Running S3 with key: #{ENV['AWS_ACCESS_KEY_ID']}, secret: #{ENV['AWS_SECRET_ACCESS_KEY']}, bucket: #{ENV['AWS_SNAPSHOTAR_BUCKET']}" @s3 = AWS::S3.new( access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], region: ENV['AWS_REGION']) @bucket = @s3.buckets[ENV['AWS_SNAPSHOTAR_BUCKET']] end ## # lists available snapshots in this storage. # # returns:: array of filenames # def index @bucket.objects.map{|obj| obj.key} end ## # loads a snapshot specified by the given +filename+. # # Params:: # +filename+:: name of the snapshot to load # # returns:: still seralized json # def show(filename) @bucket.objects[filename] end ## # creates a snapshot specified by the given +filename+ with data provided # # Params:: # +filename+:: name of the snapshot to create # +serialized_tree+:: json serialized data # def create(filename,serialized_tree) @bucket.objects[filename].write(serialized_tree) end ## # deletes a snapshot specified by the given +filename+. # # Params:: # +filename+:: name of the snapshot to delete # def delete(filename) @bucket.objects[filename].delete end end end end
class Home_placeholder def id "0" end def name "Homepage" end end
#!/usr/bin/env ruby # # Passcode derivation # http://projecteuler.net/problem=79 # # A common security method used for online banking is to ask the user for three # random characters from a passcode. For example, if the passcode was 531278, they # may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317. # # The text file, p079_keylog.txt, contains fifty successful login attempts. # # Given that the three characters are always asked for in order, analyze the file # so as to determine the shortest possible secret passcode of unknown length. # require "csv" class Array def sum inject(0, :+) end def mean sum / Float(size) end end log = CSV.foreach("p079_keylog.txt").inject([], :+) pos = {} log.each {|x| x.chars.map(&:to_i).each.with_index {|y, i| pos[y] = pos[y] ? pos[y]+[i] : [i] }} avg = {} pos.each {|x| avg[x[0]] = x[1].mean } p avg.sort_by(&:last).map(&:first).join.to_i # => 73162890
class Comment < ActiveRecord::Base belongs_to :user belongs_to :web_link attr_accessible :body after_create :remove_archives validates :body, :presence => true private # If a comment gets added, then it should be unarchived for both people. def remove_archives self.web_link.archive_links.each { |l| l.destroy } self.web_link.update_attribute(:archived, false) end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :set_locale before_action :track_user def set_locale I18n.locale = params[:locale] || I18n.default_locale end def self.default_url_options(options={}) options.merge({ :locale => I18n.locale }) end def after_sign_in_path_for(resource) stored_location_for(resource) || categories_path end def track_user Event.create!(url: request.env['REQUEST_PATH'], user_id: current_user.id) if user_signed_in? end end
require 'cloudinary' require 'redis' require 'slack-ruby-bot' if ENV["RACK_ENV"] != "production" require 'pry' end module Bot REDIS_CONN = Redis.new(:url => ENV["REDIS_URL"] || "redis://localhost:6379") class App < SlackRubyBot::App end class PicAdd < SlackRubyBot::Commands::Base command 'pic add' def self.call(client, data, match) raw = match.to_a[3].split(" ") keyword = raw[0] url = raw[1].delete!('<').delete!('>') cloudinary = Cloudinary::Uploader.upload(url) photo_url = cloudinary['secure_url'] REDIS_CONN.sadd(keyword, [photo_url]) keyword_total = REDIS_CONN.smembers(keyword).count send_message(client, data.channel, "Photo added successfully to #{keyword}, bringing the total number of pictures for `#{keyword}` to #{keyword_total}.") end end class PicHelp < SlackRubyBot::Commands::Base command 'pic help' def self.call(client, data, _match) send_message(client, data.channel, 'Go here for info: https://gist.github.com/maclover7/0e72962829e7445b976b') end end class PicList < SlackRubyBot::Commands::Base command 'pic list' def self.call(client, data, _match) keys = REDIS_CONN.keys sorted_keys = keys.sort! { |x, y| y <=> x } send_message(client, data.channel, "There are currently #{keys.count} keywords available.") sorted_keys.each do |key| photo_count = REDIS_CONN.smembers(key).count send_message(client, data.channel, "*#{key}*: #{photo_count} photos") end end end class PicMe < SlackRubyBot::Commands::Base command 'pic me' def self.call(client, data, match) keyword = match.to_a[3] photo = REDIS_CONN.smembers(keyword).sample send_message(client, data.channel, photo) end end class Ping < SlackRubyBot::Commands::Base command 'ping' def self.call(client, data, _match) client.message(text: 'pong', channel: data.channel) end end class Gif < SlackRubyBot::Commands::Base command 'gif me' def self.call(client, data, match) keyword = match.to_a[3] send_gif(client, data.channel, keyword) end end class Swanson < SlackRubyBot::Commands::Base command 'swanson me' def self.call(client, data, _match) send_gif(client, data.channel, 'swanson') end end end
class OutcomesController < ApplicationController def new @outcome = Outcome.new end def create @outcome = Outcome.new(outcome_params) if @outcome.save redirect_to @outcome else render 'new' end end def show @outcome = Outcome.find(params[:id]) end def index @outcomes = Outcome.all end def edit @outcome = Outcome.find(params[:id]) end def update @outcome = Outcome.find(params[:id]) if @outcome.update(params[:outcome].permit(:winner, :loser)) redirect_to @outcome else render 'edit' end end def destroy @outcome = Outcome.find(params[:id]) @outcome.destroy redirect_to outcomes_path end private def outcome_params params.require(:outcome).permit(:winner, :loser) end end
require 'test_helper' class TestScoresControllerTest < ActionController::TestCase setup do @test_score = test_scores(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:test_scores) end test "should get new" do get :new assert_response :success end test "should create test_score" do assert_difference('TestScore.count') do post :create, test_score: { description: @test_score.description, score: @test_score.score, test_id: @test_score.test_id, user_id: @test_score.user_id } end assert_redirected_to test_score_path(assigns(:test_score)) end test "should show test_score" do get :show, id: @test_score assert_response :success end test "should get edit" do get :edit, id: @test_score assert_response :success end test "should update test_score" do patch :update, id: @test_score, test_score: { description: @test_score.description, score: @test_score.score, test_id: @test_score.test_id, user_id: @test_score.user_id } assert_redirected_to test_score_path(assigns(:test_score)) end test "should destroy test_score" do assert_difference('TestScore.count', -1) do delete :destroy, id: @test_score end assert_redirected_to test_scores_path end end
class AuctionSerializer < ActiveModel::Serializer attributes :id, :title, :description, :price, :end_date, :created_at belongs_to :user, key: :seller has_many :bids def created_at object.created_at.strftime('%Y-%B-%d') end end
# frozen_string_literal: true # == Schema Information # # Table name: taggings # # id :integer not null, primary key # tag_id :integer not null # data_table_id :integer not null # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe Tagging, type: :model do let(:subject) { build(:tagging) } describe 'connections' do it { is_expected.to belong_to(:tag) } it { is_expected.to belong_to(:data_table) } end describe 'validations' do it { is_expected.to validate_uniqueness_of(:tag_id).scoped_to(:data_table_id) } it { is_expected.to validate_uniqueness_of(:data_table_id).scoped_to(:tag_id) } end end
require 'rails_helper' RSpec.describe Store, type: :model do before do @store = build(:store) end it "有効なstoreを持つこと" do expect(@store).to be_valid end it "store_manager_idがなければ無効であること" do @store.store_manager_id = nil expect(@store).to be_invalid end describe 'stoer_name' do it "お店の名前がない場合は無効であること" do @store.store_name = nil expect(@store).to be_invalid end end describe 'adress' do it "住所が存在した際に4文字以下は無効であること" do @store.adress = "adre" expect(@store).to be_invalid end it "住所が存在した際に5文字以上は有効であること" do @store.adress = "adres" expect(@store).to be_valid end end describe 'store_description' do it "店舗説明が存在した際に9文字以下は無効であること" do @store.store_description = SecureRandom.alphanumeric(9) expect(@store).to be_invalid end it "店舗説明が存在した際に10文字以上の場合は有効であること" do @store.store_description = SecureRandom.alphanumeric(10) expect(@store).to be_valid end end end
class CustomerOrdersController < ApplicationController before_action :set_customer_order, only: [:show, :edit, :update, :destroy] # GET /customer_orders/1 # GET /customer_orders/1.json def show end # GET /customer_orders/new def new @customer_order = CustomerOrder.new @gig = Gig.friendly.find(params[:gig_id]) end # GET /customer_orders/1/edit def edit @gig = Gig.friendly.find(params[:gig_id]) end # POST /customer_orders # POST /customer_orders.json def create @customer_order = CustomerOrder.new(customer_order_params) @gig = Gig.friendly.find(params[:gig_id]) @seller = @gig.user @customer_order.gig_id = @gig.id @customer_order.buyer_id = current_user.id @customer_order.seller_id = @seller.id @customer_order.status = 'Pending' respond_to do |format| if @customer_order.save format.html { redirect_to @customer_order.paypal_url(gig_customer_order_path(@gig, @customer_order)) } #format.json { render :show, status: :created, location: @order } else format.html { render :new } format.json { render json: @customer_order.errors, status: :unprocessable_entity } end end end # PATCH/PUT /customer_orders/1 # PATCH/PUT /customer_orders/1.json def update respond_to do |format| if @customer_order.update(customer_order_params) format.html { redirect_to @customer_order, notice: 'Customer order was successfully updated.' } format.json { render :show, status: :ok, location: @customer_order } else format.html { render :edit } format.json { render json: @customer_order.errors, status: :unprocessable_entity } end end end # DELETE /customer_orders/1 # DELETE /customer_orders/1.json def destroy @customer_order.destroy respond_to do |format| format.html { redirect_to admin_url, notice: 'Customer order was successfully destroyed.' } format.json { head :no_content } end end def sales @gigs = Gig.where(user: current_user) @customer_orders = CustomerOrder.where(seller: current_user, payment_status: 'Paid').includes(:gig, :buyer).order('created_at DESC').page(params[:page]).per(20) @pendings = CustomerOrder.where(seller: current_user, status: 'Pending', payment_status: 'Paid') end def purchases @gigs = Gig.all @customer_orders = CustomerOrder.where(buyer: current_user, payment_status: 'Paid').includes(:gig, :buyer, :seller).order('purchased_at DESC').page(params[:page]).per(20) end def earnings @gigs = Gig.where(user: current_user) @customer_orders = CustomerOrder.where(seller: current_user, status: 'Completed').includes(:gig, :buyer, :seller).order('purchased_at DESC').page(params[:page]).per(20) @pendings = CustomerOrder.where(seller: current_user, status: 'Pending', payment_status: 'Paid') end def edit_customer_order_status @customer_order = CustomerOrder.find(params[:id]) @seller = User.find(@customer_order.seller) if params[:commit] == "Pending" @customer_order.update(status: "In Progress") @customer_order.send_notification_to_buyer redirect_to :back, notice: "Status has been succesfully updated to 'In Progress'." elsif params[:commit] == "In Progress" @customer_order.update(status: "Delivered") @customer_order.send_notification_to_buyer redirect_to :back, notice: "Status has been succesfully updated to 'Delivered'." else params[:commit] == "Delivered" @customer_order.update(status: "Completed") @seller.increment!(:balance, 20) @customer_order.send_notification_to_seller redirect_to :back, notice: "You have confirmed the completion of this order. Now, you can leave a review to the seller. :)" end end private # Use callbacks to share common setup or constraints between actions. def set_customer_order @customer_order = CustomerOrder.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def customer_order_params params.require(:customer_order).permit(:name, :address_one, :address_two, :city, :state, :zipcode, :country, :email, :remarks, :gig_id, :buyer_id, :seller_id, :payment_status, :notification_params, :status, :transaction_id, :purchased_at) end end
class AddCalculatorClassToShipMethod < ActiveRecord::Migration def change add_column :ship_methods, :calculator_class, :string, null: false, limit: 256 end end
Fabricator :vino do nombre { Faker::Lorem.words(2).join } end
describe FalseClass do before { allow(self).to receive(:foo) } describe '#if_true' do before { false.if_true { self.foo } } it { expect(self).not_to have_received(:foo) } end describe '#if_false' do before { false.if_false { self.foo } } it { expect(self).to have_received(:foo).once } end end
module Motion module SettingsBundle class Configuration attr_reader :preferences, :children def initialize(&block) @preferences = [] @children = {} block.call(self) end def text(title, options = {}) preference(title, "PSTextFieldSpecifier", options, { "IsSecure" => options[:secure] || false, "KeyboardType" => options[:keyboard] || "Alphabet", "AutocapitalizationType" => options[:autocapitalization] || "Sentences", "AutocorrectionType" => options[:autocorrection] || "Default" }) end def title(title, options = {}) preference(title, "PSTitleValueSpecifier", options) end def multivalue(title, options = {}) preference(title, "PSMultiValueSpecifier", options, { "Values" => options[:values], "Titles" => options[:titles].nil? ? options[:values] : options[:titles] }) end def toggle(title, options = {}) preference(title, "PSToggleSwitchSpecifier", options, { "TrueValue" => true, "FalseValue" => false }) end def slider(title, options = {}) preference(title, "PSSliderSpecifier", options, { "MinimumValue" => options[:min], "MaximumValue" => options[:max] }) end def group(title, options = {}) group = {"Title" => title, "Type" => "PSGroupSpecifier"} group["FooterText"] = options[:footer] if options[:footer] @preferences << group end def child(title, options = {}, &block) @preferences << {"Title" => title, "File" => title, "Type" => "PSChildPaneSpecifier"}.merge(options) @children[title] = Configuration.new(&block) end private def preference(title, type, options, extras = {}) @preferences << {"Title" => title, "Key" => options[:key], "DefaultValue" => options[:default], "Type" => type}.merge(extras) end end end end
module Api module Endpoints class TeamsEndpoint < Grape::API format :json helpers Api::Helpers::CursorHelpers helpers Api::Helpers::SortHelpers helpers Api::Helpers::PaginationParameters namespace :teams do desc 'Get a team.' params do requires :id, type: String, desc: 'Team ID.' end get ':id' do team = Team.where(id: params[:id], token: headers['Token']).first || error!('Not Found', 404) present team, with: Api::Presenters::TeamPresenter end desc 'Get all the teams.' params do use :pagination end get do teams = paginate_and_sort_by_cursor(Team.where(token: headers['Token'])) present teams, with: Api::Presenters::TeamsPresenter end desc 'Create a team.' params do requires :team, type: Hash do requires :token, type: String end end post do team = create(Team, with: Api::Presenters::TeamPresenter, from: params[:team]) SlackRubyBot::Service.start! team.token team end desc 'Update an existing team.' params do requires :id, type: String, desc: 'Team id.' requires :team, type: Hash do optional :token, type: String end end put ':id' do team = Team.where(id: params[:id], token: headers['Token']).first || error!('Not Found', 404) SlackRubyBot::Service.stop! team.token team = update(team, with: Api::Presenters::TeamPresenter, from: params[:team]) SlackRubyBot::Service.start! team.token team end desc 'Delete an existing team.' params do requires :id, type: String, desc: 'Team id.' end delete ':id' do team = Team.where(id: params[:id], token: headers['Token']).first || error!('Not Found', 404) SlackRubyBot::Service.stop! team.token delete team, with: Api::Presenters::TeamPresenter end end end end end
class TimingsController < ApplicationController # GET /timings # GET /timings.xml def index @timings = Timing.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @timings } end end # GET /timings/1 # GET /timings/1.xml def show @timing = Timing.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @timing } end end # GET /timings/new # GET /timings/new.xml def new @timing = Timing.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @timing } end end # GET /timings/1/edit def edit @timing = Timing.find(params[:id]) end # POST /timings # POST /timings.xml def create @timing = Timing.new(params[:timing]) respond_to do |format| if @timing.save flash[:notice] = 'Timing was successfully created.' format.html { redirect_to(@timing) } format.xml { render :xml => @timing, :status => :created, :location => @timing } else format.html { render :action => "new" } format.xml { render :xml => @timing.errors, :status => :unprocessable_entity } end end end # PUT /timings/1 # PUT /timings/1.xml def update @timing = Timing.find(params[:id]) respond_to do |format| if @timing.update_attributes(params[:timing]) flash[:notice] = 'Timing was successfully updated.' format.html { redirect_to(@timing) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @timing.errors, :status => :unprocessable_entity } end end end # DELETE /timings/1 # DELETE /timings/1.xml def destroy @timing = Timing.find(params[:id]) @timing.destroy respond_to do |format| format.html { redirect_to(timings_url) } format.xml { head :ok } end end end
class SonicScrewDriverSerializer < ActiveModel::Serializer attributes :id, :image, :description, :link has_one :doctor end
class Tracker < ActiveRecord::Base validates :keyword, presence: true, length: { minimum: 3 } end
# frozen_string_literal: true class DeleteAccountJob < ApplicationJob def perform(account_id) return unless Account.where(id: account_id).exists? account = Account.find(account_id) Account.transaction do account.tails.delete_all account.comment_logs.delete_all account.api_vk_error_logs.delete_all account.delete end rescue StandardError => e create_logger(e) end end
require 'sinatra' require 'grape' module Springseed class API < Grape::API version 'v1', vendor: 'springseed' format :json Dir.glob('apis/**/*.rb') { |n| load n } end end
class Movie < ActiveRecord::Base image_accessor :cover_image validates :name, :presence => true, :uniqueness => true validates :cast, :presence => true has_many :keywords, :dependent => :destroy do def query_twitter collect(&:perform_search).reduce(0, :+) end end has_many :tweets, :dependent => :destroy, :inverse_of => :movie default_scope :order => "movies.released_on desc" scope :spotlight, :limit => 5 scope :this_month, lambda { where(:released_on => (1.month.ago)..Time.now) } scope :this_weekend, lambda { where(:released_on => (Time.now.beginning_of_week)..(Time.now.end_of_week)) } scope :last_weekend, lambda { where(:released_on => (1.week.ago.beginning_of_week)..(1.week.ago.end_of_week)) } scope :active, where(:disabled => false) accepts_nested_attributes_for :tweets, :allow_destroy => true def formatted_score "#{computed_score}%" rescue "N/A" end def computed_score return 0 if tweets.assesed.count == 0 (((tweets.positive.count + (tweets.mixed.count * 0.5)) * 100.0)/ tweets.assesed.count).to_i end def amplify_score ( tweets.hit.count * 100.0 ) / tweets.hit_or_flop.count end def to_param "#{id}-#{name.downcase.gsub(/[^[:alnum:]]/,'-')}".gsub(/-{2,}/,'-') end end
class PaymentTypesController < ApplicationController respond_to :json before_filter :authorize before_action :find_company , :only =>[:index , :new , :create ] before_action :get_payment_type , :only =>[:edit , :update , :destroy ] def index payment_types = @company.payment_types.select("id , name") render :json=> payment_types end def create payment_type = @company.payment_types.build(:name=> params[:payment_type][:name]) if payment_type.valid? payment_type.save result ={flag: true , :id=> payment_type.id } render :json => result else show_error_json(payment_type.errors.messages) end end def edit render :json => @payment_type end def update status = @payment_type.update_attributes(:name=> params[:name]) if status result = {flag: status } render :json=> result else show_error_json(@payment_type.errors.messages) end end def destroy if @payment_type.destroy render :json=>{flag: true} else show_error_json(user.errors.messages , flag= false) end end private def get_payment_type @payment_type = PaymentType.select("id , name").find(params[:id]) end end
class CreatePia < ActiveRecord::Migration def change create_table :pia, id:false, primary_key: :pid do |t| t.string :pid t.string :titulo t.string :cie_9 t.string :informacion t.string :normativa t.string :normativa_url t.string :snomed t.string :ancestry end execute "ALTER TABLE pia ADD PRIMARY KEY (pid);" add_index :pia, :ancestry end end
require 'spec_helper' describe 'nginx', :type => :class do let (:facts) { debian_facts } let (:pre_condition) { '$concat_basedir = "/tmp"' } let (:params) { { :config_dir => '/etc/nginx' } } describe 'without parameters' do it { should create_class('nginx') } it { should include_class('nginx::install') } it { should include_class('nginx::config') } it { should include_class('nginx::service') } it { should contain_package('nginx').with_ensure('present') } it { should contain_file('/etc/nginx').with_ensure('directory') } it { should contain_service('nginx').with( 'ensure' => 'running', 'enable' => 'true', 'hasrestart' => 'true' ) } end end
require 'test_helper' class OrderNotifierTest < ActionMailer::TestCase test "received" do mail = OrderNotifier.received(orders(:mail)) assert_equal "Book store order confirmation", mail.subject assert_equal ["test@example.com"], mail.to assert_equal ["me@fadhb.com"], mail.from #assert_match /1 x Programming Ruby 1.9/, mail.body.encoded end test "shipped" do mail = OrderNotifier.shipped(orders(:mail)) assert_equal "Book store order has shipped", mail.subject assert_equal ["test@example.com"], mail.to assert_equal ["me@fadhb.com"], mail.from #assert_match /<td>1&times;<\/td>\s*<td>Programming Ruby 1.9<\/td>/, mail.body.encoded end end
######################## Numbers to digits ######################## def number_to_digits(n) n.to_s.chars.map(&:to_i) end ######################## Digits to numbers ######################## def digits_to_number(digits) digits.reduce(0) { |a, b| a * 10 + b } end def digits_to_number_2(array) new_number = 0 array.each do |number| new_number *= 10 + number end new_number end ######################## Histogram ######################## def grayscale_histogram(image) histogram = Array.new(256, 0) row = 0 column = 0 while row < image.length column = 0 while column < image[row].length histogram[image[row][column]] += 1 column += 1 end row += 1 end histogram end def grayscale_histogram_2(image) histogram = Array.new(256, 0) image.each do |row| row.each do |col| histogram[col] += 1 end end histogram end ######################## Max scalar product ######################## def max_scalar_product(v1, v2) v1 = v1.sort v2 = v2.sort index = 0 sum = 0 until index > v1.length sum += v1[index].to_i * v2[index].to_i index += 1 end sum end ######################## Max scalar product ######################## def max_span(numbers) array_length = numbers.length index = 0 max_span = [] last_number = array_length while index < array_length while last_number > index if numbers[index] == numbers[last_number] max_span << (last_number - index + 1) break end last_number -= 1 end last_number = array_length index += 1 end max_span.max end def max_span_2(numbers) length = numbers.length max_span = [] numbers.each_with_index do |element, index| numbers.reverse.each_with_index do |last_el, last_index| if element == last_el max_span << length - (last_index + index) end end end max_span.max end ######################## Invert ######################## def invert(hash) new_hash = {} hash.each do |key, value| if new_hash[value] old_val = new_hash[value] new_hash[value] = [] new_hash[value] << old_val new_hash[value] << key new_hash[value].flatten! else new_hash[value] = key end end end ######################## Sum matrix ######################## def sum_matrix(m) array = m.flatten array.reduce(&:+) end def sum_matrix_2(m) array = m.flatten sum = 0 array.each { |x| sum += x } sum end ######################## Matrix Bombing plan ######################## def matrix_bombing_plan(matrix) result = {} matrix.each_with_index do |row, index_row| row.each_with_index do |_, index_col| bombed_matrix = bomb_matrix(matrix, index_row, index_col) result[[index_row, index_col]] = sum_matrix(bombed_matrix) end end result end def neighbours_coordinates(matrix, x, y) possible_neighbours = [ [x - 1, y - 1], [x - 1, y], [x - 1, y + 1], [x + 1, y - 1], [x + 1, y], [x + 1, y + 1], [x, y - 1], [x, y + 1] ] index = 0 neighbours = [] while index < possible_neighbours.length i, j = possible_neighbours[index] valid_indexes = (0..matrix.length) if valid_indexes.include?(i) && valid_indexes.include?(j) neighbours << [i, j] end index += 1 end neighbours end def bomb_matrix(matrix, x, y) neighbours = neighbours_coordinates(matrix, x, y) bombed_matrix = [] target_value = matrix[x][y] matrix.each_with_index do |row, index_row| row.each_with_index do |value, index_col| if neighbours.include?([index_row, index_col]) value -= target_value value = 0 if value < 0 end bombed_matrix[index_row] ||= [] bombed_matrix[index_row][index_col] ||= value end end bombed_matrix end ######################## Group ######################## def group(arr) n = 0 new_arr = [] final_arr = [] while n < arr.length current = arr[n] next_num = arr[n + 1] if current == next_num new_arr << arr[n] else new_arr << arr[n] final_arr << new_arr new_arr = [] end n += 1 end final_arr end def group_2(arr) arr.group_by { |x| x }.values end ######################## Max consecutive ######################## def max_consecutive(items) count = 1 max_count = 0 items.each_with_index do |n, i| if n == items[i + 1] count += 1 else max_count = count if count > max_count count = 1 end end max_count end
require 'aws-sdk-s3' module Stax module Aws class S3 < Sdk class << self def client @_client ||= ::Aws::S3::Client.new end def list_buckets client.list_buckets.buckets end def bucket_tags(bucket) client.get_bucket_tagging(bucket: bucket).tag_set rescue ::Aws::Errors::NoSuchEndpointError warn("socket error for #{bucket}, retrying") sleep 1 retry rescue ::Aws::S3::Errors::NoSuchTagSet [] end def bucket_region(bucket) client.get_bucket_location(bucket: bucket).location_constraint end ## get region, return us-east-1 if empty def location(bucket) l = client.get_bucket_location(bucket: bucket).location_constraint l.empty? ? 'us-east-1' : l end def put(opt) client.put_object(opt) end def get_lifecycle(bucket) client.get_bucket_lifecycle_configuration(bucket: bucket).rules end def put_lifecycle(bucket, cfg) client.put_bucket_lifecycle_configuration(bucket: bucket, lifecycle_configuration: cfg) end end end end end
class DeliveriesItemsController < ApplicationController respond_to :json def index respond_with DeliveriesItems.all end end
class Product < ActiveRecord::Base default_scope { order('title') } has_many :line_items has_many :orders, :through =>:line_items before_destroy :ensure_not_referenced_by_any_line_item def ensure_not_referenced_by_any_line_item if line_items.empty? return true else errors.add(:base, 'Line Items present') return false end end end
class Comment < ActiveRecord::Base belongs_to :user belongs_to :exercise scope :get_error_comment_by_admin, -> {joins(:user).where("role not in ('developer', 'root', 'admin') and status = 0").order(created_at: :desc)} scope :get_done_comment_by_admin, -> {joins(:user).where("role not in ('developer', 'root', 'admin') and status = 1").order(created_at: :desc)} validates :content, presence: true enum status: [:error, :done] end
class User < ActiveRecord::Base has_many :flowers has_many :comments has_many :ratings has_secure_password # has before save shit to encrypt pw? valid_email = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: valid_email }, uniqueness: { case_sensitive: false } validates :password, :username, presence: true, length: { minimum: 5 }, on: :create # so it doesnt try and validate pw on update_attributes before_create { |user| user.email.downcase! } end
Rails.application.routes.draw do resources :partners resources :customers resources :friends #get 'home/index' root 'home#index' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
module Spree module PaymentDecorator def verify!(**options) process_verification(options) end private def process_verification(**options) protect_from_connection_error do response = payment_method.verify(source, options) record_response(response) if response.success? unless response.authorization.nil? self.response_code = response.authorization source.update(status: response.params['status']) end else gateway_error(response) end end end end end Spree::Payment.prepend Spree::PaymentDecorator