text
stringlengths
10
2.61M
require 'spec_helper' describe 'pupmod::master::sysconfig' do on_supported_os.each do |os, os_facts| before :all do @extras = { :puppet_settings => { 'master' => { 'rest_authconfig' => '/etc/puppetlabs/puppet/authconf.conf' }}} end context "on #{os}" do ['PE', 'PC1'].each do |server_distribution| context "server distribution '#{server_distribution}'" do let(:puppetserver_svc) { svc = 'puppetserver' if server_distribution == 'PE' svc = 'pe-puppetserver' end svc } let(:pre_condition) { %{ service{ #{puppetserver_svc}: } } } let(:params){{ :server_distribution => server_distribution }} if server_distribution == 'PE' let(:facts){ @extras.merge(os_facts).merge( :memorysize_mb => '490.16', :pe_build => '2016.1.0' ) } it 'sets $tmpdir via a pe_ini_subsetting resource' do expect(catalogue).to contain_pe_ini_subsetting('pupmod::master::sysconfig::javatempdir').with( 'value' => %r{/pserver_tmp$}, 'path' => '/etc/sysconfig/pe-puppetserver', ) end else let(:facts){ @extras.merge(os_facts).merge(:memorysize_mb => '490.16') } puppetserver_content = File.open("#{File.dirname(__FILE__)}/data/puppetserver.txt", "rb").read it { is_expected.to contain_file('/etc/sysconfig/puppetserver').with( { 'owner' => 'root', 'group' => 'puppet', 'mode' => '0640', 'content' => puppetserver_content } )} it { is_expected.to create_class('pupmod::master::sysconfig') } it { is_expected.to contain_file('/opt/puppetlabs/puppet/cache/pserver_tmp').with( { 'owner' => 'puppet', 'group' => 'puppet', 'ensure' => 'directory', 'mode' => '0750' } )} end end end end end end
module TimeTrackerCategoriesHelper class Tree attr_reader :list_root, :list, :html, :controller def initialize(array) @list_root,@list,@html,@controller = [], {}, '', 'time_tracker_categories' array.each {|e| if e.parent_id == 0 @list_root.push(e.id) else @list[e.parent_id] = {:info => nil, :list => [] } if @list[e.parent_id].nil? @list[e.parent_id][:list].push(e.id) end if @list[e.id].nil? @list[e.id] = {:info => e, :list => []} else @list[e.id][:info] = e if @list[e.id][:info].nil? @list[e.id][:list] = [] if @list[e.id][:list].nil? end } show end private def show @list_root.each {|e| show_item(@list[e]) } end def show_item(item) @html << "<li>" unless item[:list].size == 0 @html << "<span>#{item[:info].name}</span> &nbsp; #{link_new_child(item[:info].id)} #{link_edit(item[:info].id)}" @html << "<ul>" item[:list].each {|it| show_item(@list[it]) } @html << "</ul>" else @html << "#{item[:info].name} &nbsp; #{link_new_child(item[:info].id)} #{link_edit(item[:info].id)} #{link_del(item[:info].id) }" end @html << "</li>" end def link_del(id) "<a rel=\"nofollow\" data-method=\"delete\" data-confirm=\"Are you sure?\" href=\"/#{@controller}/#{id}\" alt=\"del\"><img src=\"/images/delete.png\" height=\"16\" width=\"16\" alt=\"del\" border=\"0\"></a>" end def link_edit(id) "<a href=\"/#{@controller}/#{id}/edit\" alt=\"edit\"><img src=\"images/edit.png\" height=\"16\" width=\"16\" alt=\"edit\" border=\"0\"></a>" end def link_new_child(id) "<a href=\"/#{@controller}/#{id}/new\" alt=\"add child\"><img src=\"images/add.png\" height=\"16\" width=\"16\" alt=\"add\" border=\"0\"></a>" end def link_view_time_tracker(id) "<a href=\"/#{@controller}/#{id}\" alt=\"view time tracker list\"><img src=\"images/text_list_bullets.png\" height=\"16\" width=\"16\" alt=\"add\" border=\"0\"></a>" end end end
class AddSlugToMovie < ActiveRecord::Migration[5.0] def change add_column :movies, :slug, :string add_column :actors, :slug, :string add_column :characters, :slug, :string add_column :directors, :slug, :string add_column :genres, :slug, :string end end
class Band < ActiveRecord::Base attr_accessible :name, :photo validates :name, :presence => true has_many :artists has_many :recordings has_many :songs, :through => :recordings end
class CreateWorkspacesEquipmentJoin < ActiveRecord::Migration def change create_table :workspaces_equipment do |t| t.integer "workspaces_id" t.integer "equipment_id" end add_index :workspaces_equipment, ["workspaces_id", "equipment_id"] end end
namespace :lapis do namespace :client do task ruby: :environment do # Work with test environment ApplicationRecord.establish_connection(:test) ApiKey.where(access_token: 'test').destroy_all api_key = ApiKey.create! api_key.access_token = 'test' api_key.save! # Generate name camel_name = Rails.application.class.to_s.gsub(/::Application$/, '') gem_camel_name = "#{camel_name}Client" snake_name = camel_name.underscore gem_snake_name = "#{snake_name}_client" # Get current version number basedir = File.join(gem_snake_name, 'lib', gem_snake_name) version_file = File.join(basedir, 'version.rb') current_version = '0.1.0' new_version = '0.0.1' if File.exist?(version_file) number = File.readlines(version_file)[1].gsub(/[^0-9\.]/, '').gsub('0.0.', '').to_i new_version = '0.0.' + (number + 1).to_s end # Remove current gem if it exists FileUtils.rm_rf(gem_snake_name) # Create new gem system "bundle gem #{gem_snake_name} --mit" # Update version number content = File.read(version_file).gsub(current_version, new_version) f = File.open(version_file, 'w+') f.puts(content) f.close # Update license license = File.join(gem_snake_name, 'LICENSE.txt') content = File.read(license) content.gsub!(/(Copyright \(c\) #{Time.now.year} ).*\n/, "\\1#{INFO[:author]}\n") f = File.open(license, 'w+') f.puts(content) f.close # Parse each possible return (from Swagger) mock_methods = [] mock_methods_sigs = [] request_methods = [] request_methods_sigs = [] version = Swagger::Docs::Config.registered_apis.keys.last docs = Swagger::Docs::Generator.generate_docs(Swagger::Docs::Config.registered_apis)[version][:processed] docs.each do |doc| doc[:apis].each do |api| api[:path].gsub!(/^\//, '') path = api[:path].gsub(/^api\//, '').tr('/', '_') api[:operations].each do |op| next if op[:response_messages].first[:responseModel].nil? apicall = "#{op[:method].upcase} /#{api[:path]}" method = "#{op[:method]}_#{path}" request_methods_sigs << "#{method} (`#{apicall}`)" request_methods << %{ # #{apicall} def self.#{method}(host = nil, params = {}, token = '', headers = {}) request('#{op[:method]}', host, '/#{api[:path]}', params, token, headers) end } op[:response_messages].each do |r| status = r[:code] status == :ok if status == :success status = Rack::Utils.status_code(status) mock_method = "mock_#{path}_returns_#{r[:message].parameterize.tr('-', '_')}" mock_methods_sigs << mock_method example = r[:responseModel] app = ActionDispatch::Integration::Session.new(Rails.application) response = app.send(op[:method], '/' + api[:path], example[:query], example[:headers]) json = app.body.chomp object = nil begin object = JSON.parse(json) rescue end mock_methods << %{ def self.#{mock_method}(host = nil) WebMock.disable_net_connect! host ||= #{gem_camel_name}.host WebMock.stub_request(:#{op[:method]}, host + '/#{api[:path]}') .with(#{example}) .to_return(body: '#{json}', status: #{status}) @data = #{object.inspect} yield WebMock.allow_net_connect! end } end end end end # Get exposed functions require 'rdoc' require 'htmlentities' exposed_methods_signs = [] exposed_methods_bodies = [] exposed_gems = [] rdoc = RDoc::RDoc.new options = rdoc.load_options rdoc.options = options rdoc.store = RDoc::Store.new classes = rdoc.parse_files(['app', 'lib'])[0].instance_variable_get('@store').all_classes classes.each do |c| c.method_list.each do |m| dump = m.marshal_dump tags = dump[5].parts.map(&:parts).flatten if tags.include?('@expose') exposed_methods_signs << dump[1] body = HTMLEntities.new.decode(m.markup_code.gsub(/<span class=\"ruby-comment\">.*<\/span>/, '').gsub(/<[^>]*>/, '').gsub("\n", "\n ").gsub(/ def /, ' def self.')) exposed_gems += body.scan(/\srequire ['"]([^'"]+)['"]/).flatten exposed_methods_bodies << body end end end # Update spec (metadata and dependencies) specfile = File.join(gem_snake_name, "#{gem_snake_name}.gemspec") content = File.read(specfile) content.gsub!(/spec\.authors.*\n/, "spec.authors = ['#{INFO[:author]}']\n") content.gsub!(/spec\.email.*\n/, "spec.email = ['#{INFO[:author_email]}']\n") content.gsub!(/spec\.summary.*\n/, "spec.summary = ['#{INFO[:description]} (Client)']\n") content.gsub!(/spec\.description.*\n/, "spec.description = ['#{INFO[:description]} (Client)']\n") content.gsub!(/^end$/, " spec.add_development_dependency \"webmock\", \"~> 1.21.0\"\nend") exposed_gems.each do |dep| content.gsub!(/^end$/, " spec.add_runtime_dependency \"#{dep}\"\nend") end f = File.open(specfile, 'w+') f.puts(content) f.close # Update README readme = %{ # #{gem_camel_name} This gem is a client for #{snake_name}, which defines itself as '#{INFO[:description]}'. It also provides mock methods to test it. ## Installation Add this line to your application's Gemfile: ```ruby gem '#{gem_snake_name}' ``` And then execute: $ bundle Or install it yourself as: $ gem install #{gem_snake_name} ## Usage With this gem you can call methods from #{snake_name}'s API and also test them by using the provided mocks. The available methods are: #{request_methods_sigs.collect{ |r| "* #{gem_camel_name}::Request.#{r}" }.join("\n")} If you are going to test something that uses the '#{gem_snake_name}' service, first you need to mock each possible response it can return, which are: #{mock_methods_sigs.collect{ |r| "* #{gem_camel_name}::Mock.#{r}" }.join("\n")} You can also reuse utility functions that are exposed by '#{gem_snake_name}'. They are: #{exposed_methods_signs.collect{ |r| "* #{gem_camel_name}::Util.#{r}" }.join("\n")} ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request } f = File.open(File.join(gem_snake_name, 'README.md'), 'w+') f.puts(readme) f.close # Now the important stuff - generate the library lib = %{require '#{gem_snake_name}/version' require 'webmock' require 'net/http' module #{gem_camel_name} include WebMock::API @host = nil def self.host=(host) @host = host end def self.host @host end module Request #{request_methods.join} private def self.request(method, host, path, params = {}, token = '', headers = {}) host ||= #{gem_camel_name}.host uri = URI(host + path) klass = 'Net::HTTP::' + method.capitalize request = nil if method == 'get' querystr = params.reject{ |k, v| v.blank? }.collect{ |k, v| k.to_s + '=' + CGI::escape(v.to_s) }.reverse.join('&') (querystr = '?' + querystr) unless querystr.blank? request = klass.constantize.new(uri.path + querystr) elsif method == 'post' request = klass.constantize.new(uri.path) request.set_form_data(params) end unless token.blank? request['#{CheckConfig.get('authorization_header') || 'X-Token'}'] = token.to_s end http = Net::HTTP.new(uri.hostname, uri.port) http.use_ssl = uri.scheme == 'https' response = http.request(request) if response.code.to_i === 401 raise 'Unauthorized' else JSON.parse(response.body) end end end module Mock #{mock_methods.join} end module Util #{exposed_methods_bodies.join} end end} f = File.open(File.join(gem_snake_name, 'lib', "#{gem_snake_name}.rb"), 'w+') f.puts(lib) f.close # Compile gem system "cd #{gem_snake_name} && gem build #{gem_snake_name}.gemspec && cd .." # Finish puts puts '----------------------------------------------------------------------------------------------------------------' puts "Done! Your gem is at '#{gem_snake_name}'. Now please submit it to a remote Github repository." puts "After that, add the repository address in line 14 ('homepage') of file #{gem_snake_name}/#{gem_snake_name}.gemspec." puts "Or publish to RubyGems.org and add that URL." puts '----------------------------------------------------------------------------------------------------------------' api_key.destroy! ApplicationRecord.establish_connection(ENV['RAILS_ENV'].to_sym) end end end
object @product attributes :name, :description, :rating node :uri do |product| product_path product end node :price do |product| product.price.amount end
class AddCollectionTypeToMovieCollections < ActiveRecord::Migration def change add_column :movie_collectionsu, :collection_type_id, :integer end end
# frozen_string_literal: true class AdvertisementsController < ApplicationController def index @advertisements = advertisement_service(user_id: current_user.id).show_all end def show @advertisement = advertisement_service( status: true, advertisement_id: params[:id] ).show end def new end def create advertisement = Advertisement.new(needed_params) advertisement.user_id = current_user.id advertisement.save redirect_to advertisements_path end private # This method initialize the service # This service has an attribute called params that it will filed with the # params that the controller send def advertisement_service(hash_params) @advertisement_service ||= AdvertisementService.new(hash_params) end def needed_params params.require(:advertisement).permit( :title, :content, :price, :dwelling_type, :postal_code, :street, :exterior_number, :interior_number, :colony, :municipality, :city, :state, :country ) end end
require 'spec_helper' feature 'upload photo', %Q{ As a user I want to upload a photo So people can stalk me to my home }do #Acceptance Criteria # I am prompted for a photo # I can upload my photo from a file on my hard drive # Once the photo is uploaded, I can see a preview of the profile pic let (:user) { FactoryGirl.build(:user) } scenario 'after I create an account, I can upload a photo' do login_user(user) visit edit_user_registration_path fill_in "Current password", with: user.password attach_file('Image', 'spec/features/images/stupid.jpeg') click_button 'Update' end end
require 'rails_helper' RSpec.describe CartSession do let!(:offer) { Offer.make! } let(:session) { ActionController::TestSession.new } subject { described_class.new(session) } describe 'Included concerns' do [ CartAdd, CartClean, CartList, CartRemove, ].each do |mod| it { is_expected.to be_an(mod) } end end describe 'Initialize' do context 'new cart' do it { expect(subject.session).to have_key(:shopping_cart) } it { expect(subject.session[:shopping_cart]).to eq([]) } it { expect(subject.cart).to eq([]) } it { expect(subject.cart).to eq(subject.session[:shopping_cart]) } it 'creates session[:shopping_cart] in session when load instance' do expect { subject }.to change{ session[:shopping_cart] }.from(nil).to([]) end end context 'existing cart' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 1 } ]) end it { expect(subject.session).to have_key(:shopping_cart) } it { expect(subject.cart).to eq(subject.session[:shopping_cart]) } it 'creates session[:shopping_cart] in session when load instance' do expect { subject }.not_to change{ session[:shopping_cart] } end end end describe '#add' do before { subject } context 'new item in cart' do context 'quantity <= 3' do context 'quantity == 0' do it { expect{ subject.add(offer, 0) }.to change{ session[:shopping_cart] }.from([]).to([{"id" => offer.id, "quantity" => 1}]) } end context 'quantity < 0' do it { expect{ subject.add(offer, -1) }.to change{ session[:shopping_cart] }.from([]).to([{"id" => offer.id, "quantity" => 1}]) } end context 'quantity == 1' do it { expect{ subject.add(offer, 1) }.to change{ session[:shopping_cart] }.from([]).to([{"id" => offer.id, "quantity" => 1}]) } end context 'quantity == nil' do it { expect{ subject.add(offer, nil) }.to change{ session[:shopping_cart] }.from([]).to([{"id" => offer.id, "quantity" => 1}]) } end context 'quantity == 2' do it { expect{ subject.add(offer, 2) }.to change{ session[:shopping_cart] }.from([]).to([{"id" => offer.id, "quantity" => 2}]) } end context 'quantity == 3' do it { expect{ subject.add(offer, 3) }.to change{ session[:shopping_cart] }.from([]).to([{"id" => offer.id, "quantity" => 3}]) } end end context 'quantity > 3' do it { expect{ subject.add(offer, 4) }.not_to change{ session[:shopping_cart] } } it { expect{ subject.add(offer, 4) }.to change{ subject.errors.length }.from(0).to(1) } it { expect{ subject.add(offer, 4) }.to change{ subject.errors }.from([]).to(['Você pode comprar no máximo 3 cotas de cada oferta']) } end end context 'existing item in cart' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 1 } ]) end context 'quantity <= 3' do context 'quantity == 0' do it 'adds item' do subject.add(offer, 0) expect(session[:shopping_cart]).to eq([{"id" => offer.id, "quantity" => 2}]) end end context 'quantity < 0' do it 'adds item' do subject.add(offer, -1) expect(session[:shopping_cart]).to eq([{"id" => offer.id, "quantity" => 2}]) end end context 'quantity == 1' do it 'adds item' do subject.add(offer, 1) expect(session[:shopping_cart]).to eq([{"id" => offer.id, "quantity" => 2}]) end end context 'quantity == nil' do it 'adds item' do subject.add(offer, nil) expect(session[:shopping_cart]).to eq([{"id" => offer.id, "quantity" => 2}]) end end context 'quantity == 2' do it 'adds item' do subject.add(offer, 2) expect(session[:shopping_cart]).to eq([{"id" => offer.id, "quantity" => 3}]) end end context 'quantity == 3' do it { expect{ subject.add(offer, 3) }.not_to change{ session[:shopping_cart] } } it { expect{ subject.add(offer, 3) }.to change{ subject.errors.length }.from(0).to(1) } it { expect{ subject.add(offer, 3) }.to change{ subject.errors }.from([]).to(['Você pode comprar no máximo 3 cotas de cada oferta']) } end end context 'quantity > 3' do it { expect{ subject.add(offer, 4) }.not_to change{ session[:shopping_cart] } } it { expect{ subject.add(offer, 4) }.to change{ subject.errors.length }.from(0).to(1) } it { expect{ subject.add(offer, 4) }.to change{ subject.errors }.from([]).to(['Você pode comprar no máximo 3 cotas de cada oferta']) } end end end describe '#remove' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 3 } ]) end context 'existing item in cart' do before { subject } context '0 quantity' do let(:quantity) { 0 } it 'keeps session[:shopping_cart]' do expect { subject.remove(offer, quantity) }.not_to change{ session[:shopping_cart] } end end context '1 quantity' do let(:quantity) { 1 } it 'keeps session[:shopping_cart]' do subject.remove(offer, quantity) expect(session[:shopping_cart]).to eq([{ 'id' => offer.id, 'quantity' => 2 }]) end end context 'nil quantity' do let(:quantity) { nil } it 'keeps session[:shopping_cart]' do subject.remove(offer, quantity) expect(session[:shopping_cart]).to eq([{ 'id' => offer.id, 'quantity' => 2 }]) end end context 'in the middle quantity' do let(:quantity) { 2 } it 'keeps session[:shopping_cart]' do subject.remove(offer, quantity) expect(session[:shopping_cart]).to eq([{ 'id' => offer.id, 'quantity' => 1 }]) end end context 'max quantity' do let(:quantity) { 3 } it 'keeps session[:shopping_cart]' do expect { subject.remove(offer, quantity) }.to change{ session[:shopping_cart] }.from([{ 'id' => offer.id, 'quantity' => 3 }]).to([]) end end context 'more quantity than have' do let(:quantity) { 4 } it 'keeps session[:shopping_cart]' do expect { subject.remove(offer, quantity) }.to change{ session[:shopping_cart] }.from([{ 'id' => offer.id, 'quantity' => 3 }]).to([]) end end end context 'without item in cart' do let!(:other_offer) { Offer.make! } after do expect { subject.remove(other_offer, quantity) }.not_to change{ session[:shopping_cart] } end context '0 quantity' do let(:quantity) { 0 } it 'keeps session[:shopping_cart]' do end end context '1 quantity' do let(:quantity) { 1 } it 'keeps session[:shopping_cart]' do end end context 'nil quantity' do let(:quantity) { nil } it 'keeps session[:shopping_cart]' do end end context 'in the middle quantity' do let(:quantity) { 2 } it 'keeps session[:shopping_cart]' do end end context 'max quantity' do let(:quantity) { 3 } it 'keeps session[:shopping_cart]' do end end context 'more quantity than have' do let(:quantity) { 4 } it 'keeps session[:shopping_cart]' do end end end end describe '#clean' do context 'existing items' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 2 } ]) end it 'cleans session[:shopping_cart]' do expect { subject.clean }.to change{ session[:shopping_cart] }.from([ { 'id' => offer.id, 'quantity' => 2 } ]).to([]) end end context 'already empty cart' do let(:session) do ActionController::TestSession.new(shopping_cart: []) end it 'cleans session[:shopping_cart]' do expect { subject.clean }.not_to change{ session[:shopping_cart] } end end end describe '#items_count' do context 'empty cart' do let(:session) do ActionController::TestSession.new(shopping_cart: []) end it { expect(subject.items_count).to be_zero } end context 'cart with items' do context 'quantity == 1' do context 'with one item' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 1 } ]) end it { expect(subject.items_count).to eq(1) } end context 'with multiple items' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 1 }, { 'id' => offer.id + 1, 'quantity' => 1 } ]) end it { expect(subject.items_count).to eq(2) } end end context 'quantity > 1' do context 'with one item' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 2 } ]) end it { expect(subject.items_count).to eq(1) } end context 'with multiple items' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 3 }, { 'id' => offer.id + 1, 'quantity' => 2 } ]) end it { expect(subject.items_count).to eq(2) } end end end end describe '#cart_list' do describe CartList::CartListItem do it { is_expected.to respond_to(:offer) } it { is_expected.to respond_to(:total_price) } it { is_expected.to respond_to(:piece_price) } it { is_expected.to respond_to(:quantity) } end context 'empty cart' do it { expect(subject.cart_list).to be_empty } it { expect(subject.cart_list).to be_a(Array) } end context 'cart with items' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 2 } ]) end it 'returns an array of CartList::CartListItem' do subject.cart_list.each do |item| expect(item).to be_a(CartList::CartListItem) end end it 'size == cart.length' do expect(subject.cart_list.size).to eq(1) end it 'element.offer == offer' do expect(subject.cart_list.first.offer).to eq(offer) end it 'element.total_price == offer.value + offer.coordinator_tax + offer.operational_tax * element.quantity' do expected = offer.value + offer.coordinator_tax + offer.operational_tax expected *= 2 expect(subject.cart_list.first.total_price).to eq(expected) end it 'element.piece_price not includes quantity' do expected = offer.value + offer.coordinator_tax + offer.operational_tax expect(subject.cart_list.first.piece_price).to eq(expected) end it 'element.quantity == quantity' do expect(subject.cart_list.first.quantity).to eq(2) end context 'cart with deleted offer' do before { Order.destroy_all } it 'removes the item' do offer.destroy expect(subject.cart_list).to eq([]) end end end end describe '#total_value' do context 'empty cart' do it { expect(subject.total_value).to be_zero } end context 'cart with items' do let(:session) do ActionController::TestSession.new(shopping_cart: [ { 'id' => offer.id, 'quantity' => 2 } ]) end it 'returns sum of quantity * (value+coordinator_tax+operational_tax) + card_fees' do expected = offer.value + offer.coordinator_tax + offer.operational_tax expected *= 2 expected = ((expected * 0.04715) + 0.30).round(2) + expected expect(subject.total_value).to eq(expected) end end end end
require 'rails_helper' RSpec.describe Contact, type: :model do context "created with all its attributes" do user = User.create(name: "Josh") contact = Contact.new contact.first_name = "Tyler" contact.last_name = "Brewer" contact.email_address = "tylerbrewer02@gmail.com" contact.phone_number = contact.normalized_phone_number("614-448-6634") contact.company_name = "Contactually" contact.user_id = user.id contact.save it "has a first name" do expect(contact.first_name).to eq("Tyler") end it "has a last name" do expect(contact.last_name).to eq("Brewer") end it "has an email address" do expect(contact.email_address).to eq("tylerbrewer02@gmail.com") end it "has a phone number" do expect(contact.phone_number).to eq("614-448-6634") end it "has a company name" do expect(contact.company_name).to eq("Contactually") end it "has a user" do expect(contact.user_id).to eq(user.id) end end context "created without attributes" do it "is not valid without a first name" do no_first_name = Contact.new( last_name: "Brewer", email_address: "tylerbrewer02@gmail.com", phone_number: "614-448-6634", company_name: "Contactually", user_id: 1 ) expect(no_first_name.valid?).to eq(false) end it "is not valid without a last name" do no_last_name = Contact.new( first_name: "Tyler", email_address: "tylerbrewer02@gmail.com", phone_number: "614-448-6634", company_name: "Contactually", user_id: 1 ) expect(no_last_name.valid?).to eq(false) end it "is not valid without an email address" do no_email_address = Contact.new( first_name: "Tyler", last_name: "Brewer", phone_number: "614-448-6634", company_name: "Contactually", user_id: 1 ) expect(no_email_address.valid?).to eq(false) end it "is not valid without a phone number" do no_phone_number = Contact.new( first_name: "Tyler", last_name: "Brewer", email_address: "tylerbrewer02@gmail.com", company_name: "Contactually", user_id: 1 ) expect(no_phone_number.valid?).to eq(false) end it "is not valid without a company name" do no_company_name = Contact.new( first_name: "Tyler", last_name: "Brewer", email_address: "tylerbrewer02@gmail.com", phone_number: "614-448-6634", user_id: 1 ) expect(no_company_name.valid?).to eq(false) end it "is not valid without a user" do no_user_id = Contact.new( first_name: "Tyler", last_name: "Brewer", email_address: "tylerbrewer02@gmail.com", phone_number: "614-448-6634", company_name: "Contactually", ) expect(no_user_id.valid?).to eq(false) end end context "given various non-normalized phone numbers" do contact = Contact.new it "can normalize a number with parenthesis" do expect(contact.normalized_phone_number("(614)448-6634")).to eq("614-448-6634") end it "can normalize a number with parenthesis and extensions" do expect(contact.normalized_phone_number("(614)448-6634 x1234")).to eq("614-448-6634 x1234") end it "can normalize a number with a country code" do expect(contact.normalized_phone_number("1-614-448-6634")).to eq("614-448-6634") end it "can normalize a number with a country code and extensions" do expect(contact.normalized_phone_number("(614)448-6634 x1234")).to eq("614-448-6634 x1234") end it "can normalize a number with periods" do expect(contact.normalized_phone_number("614.448.6634")).to eq("614-448-6634") end it "can normalize a number with periods and extensions" do expect(contact.normalized_phone_number("(614)448-6634 x1234")).to eq("614-448-6634 x1234") end end end
require 'test_helper' class Resources::PowerBooksControllerTest < ActionController::TestCase # :nodoc: test "should default to JSON" do get :index assert_response :success assert_equal "application/vnd.application-v4+json; charset=utf-8", @response.headers["Content-Type"] end test "should negotiate a typical JSON header" do @request.accept = "application/json" get :index assert_response :success assert_equal "application/vnd.application-v4+json; charset=utf-8", @response.headers["Content-Type"] end test "should negotiate a typical XML header" do @request.accept = "application/xml" get :index assert_response :success assert_equal "application/vnd.application-v4+xml; charset=utf-8", @response.headers["Content-Type"] end test "should negotiate format and version" do @request.accept = "application/vnd.application-v1+xml" get :index assert_response :success assert_equal "application/vnd.application-v1+xml; charset=utf-8", @response.headers["Content-Type"] end test "should fall back on JSON suffix" do get :index, :format => :json assert_response :success assert_equal "application/vnd.application-v4+json; charset=utf-8", @response.headers["Content-Type"] end test "should fall back on XML suffix" do get :index, :format => :xml assert_response :success assert_equal "application/vnd.application-v4+xml; charset=utf-8", @response.headers["Content-Type"] end test "should not accept an invalid format header" do @request.accept = "text/html" get :index assert_response :not_acceptable end test "should not accept an invalid format suffix" do get :index, :format => :html assert_response :not_acceptable end test "should not accept conflicting formats" do @request.accept = "application/vnd.application-v1+xml" get :index, :format => :json assert_response :conflict, @response.body end test "should not accept conflicting versions" do @request.accept = "application/vnd.application-v1+xml" get :index, :v => 2 assert_response :conflict end test "should not accept invalid versions" do get :index, :v => 5 assert_response :not_acceptable end test "should set the order" do get :index, :order => "created_at DESC" assert_response :success, @response.body assert_equal "created_at DESC", @controller.send(:options)[:order] end test "should set the limit" do get :index, :limit => "9" assert_response :success assert_equal "9", @controller.send(:options)[:limit] end test "should not allow large limits" do get :index, :limit => "101" assert_response :not_acceptable end test "should not allow zero limits" do get :index, :limit => "0" assert_response :not_acceptable end test "should not allow negative limits" do get :index, :limit => "-1" assert_response :not_acceptable end test "should set the offset" do get :index, :offset => "20" assert_response :success assert_equal "20", @controller.send(:options)[:offset] end test "should not allow invalid offsets" do %w(-1 1.0 goooal).each do |invalid_offset| get :index, :offset => invalid_offset assert_response :not_acceptable end end end
require 'stax/aws/kms' module Stax module Kms def self.included(thor) thor.desc(:kms, 'KMS subcommands') thor.subcommand(:kms, Cmd::Kms) end end module Cmd class Kms < SubCommand no_commands do def stack_kms_keys Aws::Cfn.resources_by_type(my.stack_name, 'AWS::KMS::Key') end end desc 'ls', 'list kms keys for stack' def ls print_table stack_kms_keys.map { |r| k = Aws::Kms.describe(r.physical_resource_id) [k.key_id, k.key_state, k.creation_date, k.description] } end end end end
class EventsController < ApplicationController before_filter :init_location, :only => [:new, :create] privilege_required 'manage site', :on => :current_user, :unless => :auth_token? def index # show event cities, assume they are the densest cities @event_cities = City.min_density(City.popular_density).order_by_density(:include => :state).sort_by { |o| o.name } # @event_cities = City.with_events.order_by_density(:include => :state).sort_by { |o| o.name } end def import @city = City.find_by_name(params[:city].titleize, :include => :state) unless params[:city].blank? if params[:city].blank? # queue jobs Delayed::Job.enqueue(EventJob.new(:method => 'import_all', :limit => 100), EventJob.import_priority) Delayed::Job.enqueue(SphinxJob.new(:index => 'appointments'), -1) Delayed::Job.enqueue(EventJob.new(:method => 'set_event_counts'), -1) flash[:notice] = "Importing all city events" elsif @city.blank? flash[:error] = "Could not find city #{params[:city]}" else # queue jobs Delayed::Job.enqueue(EventJob.new(:method => 'import_city', :city => @city.name, :region => @city.state.name, :limit => 10), EventJob.import_priority) Delayed::Job.enqueue(SphinxJob.new(:index => 'appointments'), -1) Delayed::Job.enqueue(EventJob.new(:method => 'set_event_counts'), -1) flash[:notice] = "Importing #{@city.name} events" end redirect_to events_path and return end def remove # queue job Delayed::Job.enqueue(EventJob.new(:method => 'remove_past'), 3) Delayed::Job.enqueue(SphinxJob.new(:index => 'appointments'), -1) Delayed::Job.enqueue(EventJob.new(:method => 'set_event_counts'), -1) flash[:notice] = "Removing past events" redirect_to events_path and return end def new # @location, @company initialized in before filter @repeat_options = ["Does Not Repeat", "Every Weekday (Monday - Friday)", "Daily", "Weekly"] end def create # @location, @company initialized in before filter @name = params[:name].to_s @dstart = params[:dstart].to_s @tstart = params[:tstart].to_s @tend = params[:tend].to_s # build dtstart and dtend @dtstart = "#{@dstart}T#{@tstart}" @dtend = "#{@dstart}T#{@tend}" # build start_at and end_at times @start_at_utc = Time.parse(@dtstart).utc @end_at_utc = Time.parse(@dtend).utc # get recurrence parameters @freq = params[:freq].to_s.upcase @byday = params[:byday].to_s.upcase @until = params[:until].to_s @interval = params[:interval].to_i if !@freq.blank? # build recurrence rule from rule components tokens = ["FREQ=#{@freq}"] unless @byday.blank? tokens.push("BYDAY=#{@byday}") end unless @until.blank? tokens.push("UNTIL=#{@until}T000000Z") end @recur_rule = tokens.join(";") end # build appointment options hash; events are always public and marked as 'free' options = Hash[:company => @company, :name => @name, :creator => current_user, :start_at => @start_at_utc, :end_at => @end_at_utc, :mark_as => Appointment::FREE, :public => true] # add optional recurrence if specified options[:recur_rule] = @recur_rule if !@recur_rule.blank? # create event, possibly recurring @appointment = @location.appointments.create(options) if @appointment.valid? flash[:notice] = "Created event #{@name}" else @error = true flash[:error] = "Could not create event #{@name}" end respond_to do |format| format.html do if @error render(:action => 'new') else redirect_to(location_path(@location)) end end end end def show # @location, @company initialized in before filter end protected def init_location @location = Location.find(params[:location_id].to_i) @company = @location.company end end
class ProductsController < ApplicationController include CommonHelper load_and_authorize_resource before_action :find_product, only: [:update, :destroy, :get_product_ajax] def index per_page = params[:per_page] ? params[:per_page].to_i : Product::PAGE_SIZE page_index = DEFAULT_PAGE_INDEX unless params[:page].nil? page_index = params[:page].to_i end unless params[:group_id].nil? group_id = params[:group_id].to_i end name = params[:search_name] unless params[:search_name].nil? category_id = params[:search_category_id] ? params[:search_category_id].to_i : 0 @products = Product.includes(:category) .by_group(group_id) .by_name(name) .by_category(category_id) .order(category_id: :asc) .page(page_index).per(per_page) if @products.any? @total_records = @products.size @start_count = 1 if page_index > 1 @start_count = per_page * (page_index - 1) + 1 end @category_count_data = Hash.new(0) @products.each do |product| @category_count_data[product.category_id] += 1 end else @total_records = 0 end @categories = get_select_categories true, false @categories_select = get_select_categories true, true end def create @product = Product.new product_params if @product.save flash[:success] = t "model.product.message.add_success" msg = {:status => "true", :product => @product} respond_to do |format| format.json {render :json => msg} end else @errors = @product.errors.messages msg = {:status => "false", :errors => @errors} respond_to do |format| format.json {render :json => msg} end end end def update if @product.update product_params flash[:success] = t "model.product.message.update_success" msg = {:status => "true", :product => @product} respond_to do |format| format.json {render :json => msg} end else @errors = @product.errors.messages msg = {:status => "false", :errors => @errors} respond_to do |format| format.json {render :json => msg} end end end def destroy @product.delete flash[:success] = t "model.product.message.deleted_success" respond_to do |format| format.html { redirect_to group_products_path } end end def get_product_ajax respond_to do |format| format.json {render :json => @product} end end def post_product_by_category_ajax @products = Product.by_group(params[:group_id].to_i) .by_category(params[:category_id].to_i) render template: "transactions/_product_checkbox", layout: false end private def product_params if params[:product][:is_shared].to_i == 1 params[:product][:group_id] = 0 else params[:product][:group_id] = params[:group_id].to_i end params.require(:product).permit(:name, :category_id, :group_id, :is_shared) end def find_product @product = Product.find_by_id params[:id] if @product.nil? flash[:danger] = t "model.product.message.not_found" redirect_to group_products_url end end end
# frozen_string_literal: true require "dry/inflector" module Dry module Types Inflector = Dry::Inflector.new end end
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc. # Authors: Adam Lebsack <adam@holonyx.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. module Restore module Worker module_require_dependency :filesystem, 'worker' class Samba < Restore::Worker::Filesystem include GetText bindtextdomain("restore") class << self def list_directory(path, target_options) require 'smb' url = "smb://#{target_options['username']}:#{target_options['password']}@#{target_options['hostname']}#{path}" begin children = [] SMB::Dir.open url do |d| d.each do |f| f == '.' and next f == '..' and next file = {:filename => f} begin smbfile = SMB.open(url+'/'+f) stat = SMB.stat(url+'/'+f) file[:type] = (smbfile.class == SMB::File) ? 'F' : 'D' file[:size] = (smbfile.class == SMB::File) ? stat.size : nil file[:mtime] = stat.mtime rescue Errno::EACCES => e logger.info 'Permission denied' file[:error] = 'Permission denied' rescue => e logger.info e.to_s file[:error] = e.to_s end children << file end # d.each end # Dir.open return {:children => children, :loaded => true} rescue Errno::ECONNREFUSED raise _('Connection refused') end # begin end # def list_directory end end # class Samba end # module Worker end # module Restore
json.array!(@flash_cards) do |flash_card| json.extract! flash_card, :id, :term, :img, :definition, :user_id json.url flash_card_url(flash_card, format: :json) end
class StimulusGenerator < Rails::Generators::Base source_root File.expand_path('templates', __dir__) argument :controller_name, type: :string, default: false argument :action_name, type: :string, default: false attr_accessor :stimulus_path, :controller_pattern def set_up @stimulus_path = "app/javascript/controllers/#{controller_name}/#{action_name}_controller.js" @controller_pattern = "#{controller_name.split('/').join('--')}--#{action_name}" end def generate_stimulus template 'controller.js.erb', stimulus_path end end
require 'test_helper' class Links::Game::HockeyVizGameOverviewTest < ActiveSupport::TestCase test "#site_name" do assert_equal "Hockey Viz", Links::Game::HockeyVizGameOverview.new.site_name end test "#description" do assert_equal "Game Overview", Links::Game::HockeyVizGameOverview.new.description end test "#url" do season = seasons(:fourteen) team = teams(:caps) game = games(:game_one) game_type = "regular" url = "http://hockeyviz.com/game/2014021201" link = Links::Game::HockeyVizGameOverview.new(team: team, season: season, game: game, game_type: game_type) assert_equal url, link.url end test "#group" do assert_equal 4, Links::Game::HockeyVizGameOverview.new.group end test "#position" do assert_equal 2, Links::Game::HockeyVizGameOverview.new.position end end
require 'test/test_helper' require 'build_result' class BuildResultTest < Test::Unit::TestCase def test_success_in_hash_determines_success assert BuildResult.new(:succeeded? => true).succeeded? assert_equal false, BuildResult.new(:succeeded? => false).succeeded? end def test_success_defaults_to_failed assert_equal false, BuildResult.new.succeeded? end def test_minutes_in_hash_reported_as_minutes assert_equal 2, BuildResult.new(:minutes => 2).minutes end def test_minutes_defaults_to_zero assert_equal 0, BuildResult.new.minutes end def test_seconds_in_hash_reported_as_seconds assert_equal 2, BuildResult.new(:seconds => 2).seconds end def test_seconds_defaults_to_zero assert_equal 0, BuildResult.new.seconds end def test_computes_time_in_minutes assert_equal 3.75, BuildResult.new(:seconds => 45, :minutes => 3).time end def test_test_counts_default_to_empty_array assert_equal [], BuildResult.new.test_counts end def test_date_defaults_to_year_2000 assert_equal DateTime.civil(2000,1,1,0,0,0), BuildResult.new.date end def test_total_number_of_tests assert_equal 127, BuildResult.new(:test_counts => [123,4]).total_number_of_tests end def test_nice_time_gets_plurals_right assert_equal "0 minutes, 0 seconds", BuildResult.new(:seconds => 0, :minutes => 0).nice_time assert_equal "1 minute, 1 second", BuildResult.new(:seconds => 1, :minutes => 1).nice_time assert_equal "2 minutes, 2 seconds", BuildResult.new(:seconds => 2, :minutes => 2).nice_time end def test_augment_adds_new_attributes augmented_build = BuildResult.new(:seconds => 45, :minutes => 3).augment_with(:test_coverage => 34) assert_equal 34, augmented_build.test_coverage end def test_augment_keeps_old_attributes augmented_build = BuildResult.new(:seconds => 45, :minutes => 3).augment_with(:test_coverage => 34) assert_equal 45, augmented_build.seconds end def test_augment_overwrites_old_attributes augmented_build = BuildResult.new(:seconds => 45, :minutes => 3).augment_with(:minutes => 4) assert_equal 4, augmented_build.minutes end end
class CreatePens < ActiveRecord::Migration[5.2] def change create_table :pens do |t| t.string :type t.string :color t.references :student end end end
class Customer < ActiveRecord::Base has_many :cart_items, dependent: :destroy def add_product(id, product_id, quantity_ordered) cart_item =CartItem.new( customer_id: id, product_id: product_id, quantity_ordered: quantity_ordered) cart_items << cart_item #appends a value cart_item #returns a value end def total_price cart_items.to_a.sum { |item| item.sub_total } end end
require 'test_helper' class AdmissionTest < ActiveSupport::TestCase def setup @admission = Admission.create(moment: DateTime.new(2012, 07, 11, 20, 10, 0)) @patient = Patient.create(first_name: "Mr", middle_name: "Doctor", last_name: "Strange", dob: DateTime.now, gender: "male") @diagnoses = Diagnosis.create(coding_system: "test_system", code: "test code", description: "sick", patient_id: @patient.id) @symptom = Symptom.create(description: "Upset Tummy") @observation = Observation.create(description: "Patient has explosive diarrhea", moment: DateTime.now) end test "admission should be able to have a list of patients" do @admission.patients << @patient assert_equal @patient, @admission.patients.first end test "admission should be able to have a list of diagnosis" do @admission.diagnoses << @diagnoses assert_equal @diagnoses, @admission.diagnoses.first end test "admission should be able to have a list of symptoms" do @admission.symptoms << @symptom assert_equal @symptom, @admission.symptoms.first end test "admission should be able to have a list of observations" do @admission.observations << @observation assert_equal @observation, @admission.observations.first end end
class CreateSpeaks < ActiveRecord::Migration[5.2] def change create_table :speaks do |t| t.text :text t.string :field t.string :subject t.integer :st_user_id t.timestamps end end end
module Cms::CrudFilter extend ActiveSupport::Concern include SS::CrudFilter included do menu_view "cms/crud/menu" before_action :set_item, only: [:show, :edit, :update, :delete, :destroy, :lock, :unlock] end private def append_view_paths append_view_path "app/views/ss/crud" append_view_path "app/views/cms/crud" end public def index raise "403" unless @model.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) @items = @model.site(@cur_site). allow(:read, @cur_user, site: @cur_site). order_by(_id: -1). page(params[:page]).per(50) end def show raise "403" unless @item.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) render end def new @item = @model.new pre_params.merge(fix_params) raise "403" unless @item.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) end def create @item = @model.new get_params raise "403" unless @item.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) render_create @item.save end def edit raise "403" unless @item.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) if @item.is_a?(Cms::Addon::EditLock) unless @item.acquire_lock redirect_to action: :lock return end end render end def update @item.attributes = get_params @item.in_updated = params[:_updated] if @item.respond_to?(:in_updated) raise "403" unless @item.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) render_update @item.update end def delete raise "403" unless @item.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) render end def destroy raise "403" unless @item.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) render_destroy @item.destroy end def lock if @item.acquire_lock(force: params[:force].present?) render else respond_to do |format| format.html { render } format.json { render json: [ t("views.errors.locked", user: @item.lock_owner.long_name) ], status: :locked } end end end def unlock unless @item.locked? respond_to do |format| format.html { redirect_to(action: :edit) } format.json { head :no_content } end return end raise "403" if !@item.lock_owned? && !@item.allowed?(:unlock, @cur_user, site: @cur_site, node: @cur_node) if @item.release_lock(force: params[:force].present?) respond_to do |format| format.html { redirect_to(action: :edit) } format.json { head :no_content } end else respond_to do |format| format.html { render file: :show } format.json { render json: [ t("views.errors.locked", user: @item.lock_owner.long_name) ], status: :locked } end end end end
class Provider < ActiveRecord::Base has_many :product_providers, dependent: :destroy has_many :products, through: :product_providers has_many :stock_provisions validates :nom, presence: true validates :reference, presence: true accepts_nested_attributes_for :product_providers, :allow_destroy => true end
class Player attr_accessor :name, :choice def initialize(name, choice) @name = name @choice = choice end end
require_relative '../../lib/modules/method_missing' ### # # CreditDecorator # # Adds display logic to the credit business object. # # Used by payment decorator . # ## # class CreditDecorator include ActionView::Helpers::NumberHelper include MethodMissing include NumberFormattingHelper def credit @source end def initialize credit @source = credit end def amount to_decimal credit.amount end def owing to_decimal charge_debt end # payment # Payment amounts have different behaviour when new and when edited. # When new we take the amount owing as the default # When editing we take the amount already paid. # def payment if credit.new_record? to_decimal_edit charge_debt else to_decimal_edit credit.amount end end private def charge_debt Debit.debt_on_charge(charge_id) end end
class ExtrasController < ApplicationController before_action :set_extra, only: [:show, :edit, :update, :destroy] before_action :form_variables, only: [:new, :edit, :create, :update] # GET /extras # GET /extras.json def index @extras = Extra.all end # GET /extras/1 # GET /extras/1.json def show end # GET /extras/new def new @extra = Extra.new @workers = [] end # GET /extras/1/edit def edit @workers = Worker.where(workshop_id: @extra.workshop_id) end # POST /extras # POST /extras.json def create @extra = Extra.new(extra_params) @workers_create = Worker.where(workshop_id: params[:extra][:workshop_id]) respond_to do |format| if @extra.save format.html { redirect_to extras_path, notice: 'تم أضافة المكافئة' } format.json { render :show, status: :created, location: @extra } else format.html { render :new } format.json { render json: @extra.errors, status: :unprocessable_entity } end end end # PATCH/PUT /extras/1 # PATCH/PUT /extras/1.json def update @workers = Worker.where(workshop_id: params[:extra][:workshop_id]) respond_to do |format| if @extra.update(extra_params) format.html { redirect_to extras_path, notice: 'تم تحديث المكافئة' } format.json { render :show, status: :ok, location: @extra } else format.html { render :edit } format.json { render json: @extra.errors, status: :unprocessable_entity } end end end # DELETE /extras/1 # DELETE /extras/1.json def destroy @extra.destroy respond_to do |format| format.html { redirect_to extras_url, notice: 'تم ألغاء المكافئة' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_extra @extra = Extra.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def extra_params params.require(:extra).permit(:cost, :worker_id, :workshop_id) end def form_variables @workshops = Workshop.all end end
class SearchesController < ApplicationController def search begin return render json: "Please enter query", status: 400 unless request.query_parameters['query'] query = request.query_parameters['query'] @movies = Movie.search_movie_title(query) @news = News.search_news_content(query) @celebrities = Celebrity.search_celebrity(query) rescue Exception => exc return render json: { "error" => exc.message }, status: 500 end end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable # user will have many listings to sell so user will create listing # when user is deleted lsitings will delete as well has_many :listings, dependent: :destroy # one user can have many orders so orders will have user_id as foreign key has_many :orders, dependent: :destroy # this is for mailbox, so that user can message each other acts_as_messageable def name "User #{id}" end def mailboxer_email(object) nil end end
class ApplicationController < ActionController::Base protect_from_forgery before_filter :setup def setup # Mailchimp API Key @mailchimp_api_key = 'API_KEY' # This site's domain name, including the www. if required (ie: google.com): @sitedomain = 'DOMAIN.TLD' # Title tag for the site: @sitetitle = 'Title' # Keywords for the site: @sitekeywords = 'key, words' # Description for the site, also used in Tweet so keep it short: @sitedescription = 'DESCRIPTION' # Blurb about site, displayed on main page: @siteblurb = 'BLURB' # Google Analytics code for the site: @sitegoogleanalytics = 'UA-#######-##' # Twitter name for site: @twittername = 'TWITTERUSERNAME' end end
class ProductMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.product_mailer.product_deleted.subject # def product_deleted product, orders @product = product @orders = orders mail to: "huatam391@gmail.com", subject: "Warning exist orders with product was deleted" end end
class CourseStudent < ApplicationRecord validates_presence_of :grade belongs_to :student belongs_to :course def name Student.find(self.student_id).name end end
# frozen_string_literal: true require 'ipaddr' ## # Holds helper methods for friendly resources view template. module FriendlyResourcesHelper # @return [String] def friendly_resource_name(friendly_resource) return friendly_resource.name if friendly_resource 'Unknown' end # @return [String] def friendly_resource_ip(friendly_resource) return IPAddr.new(friendly_resource.ip_address, Socket::AF_INET).to_s if friendly_resource 'Unknown' end # @return [String] def page_title_for_friendly_resources_view(page_details) "FriendlyResources | #{page_details}" end end
require 'acfs/service/middleware' module Acfs # @api private # class Runner include Service::Middleware attr_reader :adapter def initialize(adapter) @adapter = adapter @running = false end # Process an operation. Synchronous operations will be run # and parallel operations will be queued. # def process(op) ::ActiveSupport::Notifications.instrument 'acfs.operation.before_process', operation: op op.synchronous? ? run(op) : enqueue(op) end # Run operation right now skipping queue. # def run(op) ::ActiveSupport::Notifications.instrument 'acfs.runner.sync_run', operation: op do op_request(op) {|req| adapter.run req } end end # List of current queued operations. # def queue @queue ||= [] end # Enqueue operation to be run later. # def enqueue(op) ::ActiveSupport::Notifications.instrument 'acfs.runner.enqueue', operation: op do if running? op_request(op) {|req| adapter.queue req } else queue << op end end end # Return true if queued operations are currently processed. # def running? @running end # Start processing queued operations. # def start return if running? enqueue_operations start_all rescue queue.clear raise end def clear queue.clear adapter.abort @running = false end private def start_all @running = true adapter.start ensure @running = false end def enqueue_operations while (op = queue.shift) op_request(op) {|req| adapter.queue req } end end def op_request(op) return if Acfs::Stub.enabled? && Acfs::Stub.stubbed(op) req = op.service.prepare op.request return unless req.is_a? Acfs::Request req = prepare req return unless req.is_a? Acfs::Request yield req end end end
class AddTeamLogos < ActiveRecord::Migration[5.2] def change add_column(:teams, :svglogo, :text) remove_column(:teams, :created_at, :datetime) remove_column(:teams, :updated_at, :datetime) end end
require "spec_helper" describe App do include Rack::Test::Methods def app App end describe "heartbeat" do it "should return 'Alive'" do get "/status/heartbeat" last_response.ok?.should be_true last_response.body.should == "Alive" end end describe "db" do before do get "/db" end it "should return ok" do last_response.ok?.should be_true end it "should mention Sinatra Sample" do last_response.body.should =~ /Sinatra Sample/ end end end
class Step < ApplicationRecord belongs_to :level has_many :questions def self.first_step where(order: 0, level_id: Level.first_level.id).first end def next level.steps.find { |s| s.order == order + 1 } end end
class Combustible < ActiveRecord::Base attr_accessible :nombre has_many :precio def to_s self.nombre end def self.find_by_slug slug Combustible.all.detect { |c| c.slug == slug } end def self.find_by_id_or_slug id_or_slug combustible = Combustible.find_by_slug(id_or_slug) combustible.nil? ? Combustible.find(id_or_slug) : combustible end def slug self.nombre.downcase.strip.gsub(" ", "-") end end
require 'bundler' Bundler::GemHelper.install_tasks task :default => :test require 'rake/testtask' Rake::TestTask.new do |t| t.pattern = "test/*_test.rb" end begin require 'rocco/tasks' require 'rake/clean' Rocco::make 'docs/' desc 'Build rocco docs' task :docs => :rocco directory 'docs/' desc 'Build docs and open in browser for the reading' task :read => :docs do sh 'open docs/index.html' end file 'docs/index.html' => 'lib/require_relative.rb' do |f| cp "docs/lib/require_relative.html", "docs/index.html" cp "docs/lib/require_relative.html", "docs/require_relative.html" end file 'docs/require_relative/version.html' => 'lib/require_relative/version.rb' do |f| mkdir_p "docs/require_relative" cp "docs/lib/require_relative/version.html", "docs/require_relative/version.html" end task :docs => 'docs/index.html' task :docs => 'docs/require_relative/version.html' CLEAN.include 'docs/index.html' # Alias for docs task task :doc => :docs desc 'Update gh-pages branch' task :pages => ['docs/.git', :docs] do rev = `git rev-parse --short HEAD`.strip Dir.chdir 'docs' do sh "git add *.html" sh "git add require_relative/*.html" sh "git commit -m 'rebuild pages from #{rev}'" do |ok,res| if ok verbose { puts "gh-pages updated" } sh "git push -q o HEAD:gh-pages" end end end end file 'docs/.git' => ['docs/', '.git/refs/heads/gh-pages'] do |f| sh "cd docs && git init -q && git remote add o ../.git" if !File.exist?(f.name) sh "cd docs && git fetch -q o && git reset -q --hard o/gh-pages && touch ." end CLOBBER.include 'docs/.git' rescue LoadError warn "#$! -- rocco tasks not loaded." end
# encoding: utf-8 # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Mayor.create(:name => 'Daley', :city => cities.first) clients = Client.create([ { :full_name => 'Иванов Сергей Петрович' }, { :full_name => 'Тющенко Владимир Николаевич' }, { :full_name => 'Сорокина Ирина Геннадьевна'}])
class PartialRendererGenerator < Rails::Generator::NamedBase def initialize(runtime_args, runtime_options = {}) super if runtime_args[0] == 'go' options[:file_name] = 'pagination' else options[:file_name] = runtime_args[0] end if options[:format].nil? options[:format] = 'haml' end end def manifest record do |m| m.file "pagination.#{options[:format]}", "app/views/_#{options[:file_name]}.#{options[:format]}" end end def add_options!(opt) opt.separator '' opt.separator 'Options:' opt.on("--haml", "Generate haml template") { |v| options[:format] = "haml"; } opt.on("--erb", "Generate erb template") { |v| options[:format] = "erb"; } end end
class CreateCourses < ActiveRecord::Migration def change create_table :courses do |t| t.string :name t.string :by t.references :courses_site, index: true, foreign_key: true t.integer :rating t.integer :complete t.text :description t.text :learnt t.timestamps null: false end end end
require 'test_helper' require 'mocha' class FacebookerQueueWorkerTest < ActiveSupport::TestCase context 'a FacebookerQueueWorker instance' do setup do @worker = FacebookerQueueWorker.new end context 'calling #facebooker_session' do should 'return a Facebooker::CanvasSession instance' do assert_equal @worker.send(:facebooker_session).class, Facebooker::CanvasSession end end context 'calling #queue_service_adapter' do should 'delegate to #facebooker_session' do session_mock = mock adapter_mock = mock session_mock.expects(:queue_service_adapter).returns(adapter_mock) @worker.stubs(:facebooker_session).returns(session_mock) assert_equal @worker.send(:queue_service_adapter), adapter_mock end end context 'calling #process_next!' do should 'delegate the next message to the #facebooker_session' do job = { :method => 'a.facebookMethod', :params => { :key => 'value' }, :use_session => true, :session_key => 'a key', :uid => 654654654, :expires => 0 } adapter_mock = mock adapter_mock.expects(:get).returns(job) @worker.stubs(:queue_service_adapter).returns(adapter_mock) session_mock = mock session_mock.expects(:secure_with!).with(job[:session_key], job[:uid], job[:expires]) session_mock.expects(:post_without_async).with(job[:method], job[:params], job[:use_session]) @worker.stubs(:facebooker_session).returns(session_mock) @worker.process_next! end end end end
class Fixnum def closest_fibonacci raise "Can only calculate closest fibonacci of number > 0" if self <= 0 find_fibonacci(self) end private @fibonacci_sequence = [0, 1] class << self attr_accessor :fibonacci_sequence end def find_fibonacci(num) best_fibonacci = -1 best_fibonacci = 0 if num == 1 last_index = -1 while best_fibonacci < 0 last_fibonacci = Fixnum.fibonacci_sequence[last_index] prev_fibonacci = Fixnum.fibonacci_sequence[last_index - 1] if last_fibonacci >= num && prev_fibonacci < num best_fibonacci = prev_fibonacci elsif prev_fibonacci >= num last_index -= 1 else Fixnum.fibonacci_sequence << last_fibonacci + prev_fibonacci end end best_fibonacci end end
# frozen_string_literal: true # Challange 1 require('json') require('net/http') # class users request # @author Elton Fonseca class UsersRequest def initialize @file = File.open('users.json', 'w') @uri = URI('https://reqres.in/api/users') @total_pages = json_to_object(_request(@uri)).total_pages end def users build_json do (1..@total_pages).each do |page| write_users(page) write_timestamp write_tab(page) end end end private def build_json @file.write "[\n" yield @file.write ']' end def write_users(page) @file.write "\t{\n\t\t\"user_page_#{page}\": " @uri.query = URI.encode_www_form({ page: page }) users = customize_object(json_to_object(_request(@uri)).data) @file.puts users.to_json + ',' end def _request(uri) Net::HTTP.get_response(uri).body end def write_timestamp @file.write "\t\t\"timestamp\": " @file.puts "\"#{Time.now.strftime('%H:%M:%S:%3N')}\"" end def write_tab(page) page < @total_pages ? @file.puts("\t},") : @file.puts("\t}") end def customize_object(array) array.map do |data| { name: "#{data.first_name} #{data.last_name}", email: data.email } end end def json_to_object(json_format) JSON.parse(json_format, object_class: OpenStruct) end end
class CreatingASurveyForUserContext < ApiBaseContext def initialize(user, params) super(user) @params = params end def execute survey = Survey.new(params_for_survey) survey.save survey end private def params_for_survey @params. require(:survey). permit(:checklist_id, check_item_results_attributes: [:check_item_id, :value]). merge({user_id: @user.id}) end end
###################################################### # Example usage - since this is in PMApplication ###################################################### # app.alert(title: "Hey There", message: "Want a sandwich?") do |choice| # case choice # when "OK" # mp "Here's your sandwich" # when "Cancel" # mp "Fine!" # end # end # # Example of alert with input # app.alert(title: "What's your name?", style: :input) do |choice, input_text| # mp "User clicked #{choice} and typed #{input_text}" # end # Generic AlertDialog class AlertDialog < Android::App::DialogFragment def initialize(options={}, &block) # Defaults @options = { theme: Android::App::AlertDialog::THEME_HOLO_LIGHT, title: "Alert!", message: nil, positive_button: "OK", negative_button: "Cancel", positive_button_handler: self, negative_button_handler: self, style: nil, show: true }.merge(options) @callback = block self.show if @options[:show] self end def show(activity=rmq.activity) super(activity.fragmentManager, "alert_dialog") end def onCreateDialog(saved_instance_state) builder = Android::App::AlertDialog::Builder.new(activity, @options[:theme]) builder.title = @options[:title] builder.message = @options[:message] # Add buttons if they are set builder.setPositiveButton(@options[:positive_button], @options[:positive_button_handler]) if @options[:positive_button] builder.setNegativeButton(@options[:negative_button], @options[:negative_button_handler]) if @options[:negative_button] # Add custom view? @options[:view] = simple_text_view if @options[:style] == :input builder.view = @options[:view] if @options[:view] # DONE! builder.create end def simple_text_view # Set up the input input = Potion::EditText.new(activity) input.singleLine = true input.id = @text_view_id = Potion::ViewIdGenerator.generate # possible input types - future feature #input.inputType = (Android::Text::InputType.TYPE_CLASS_TEXT | Android::Text::InputType.TYPE_TEXT_VARIATION_PASSWORD) input end def onClick(dialog, id) button_text = (id == Android::App::AlertDialog::BUTTON_POSITIVE) ? @options[:positive_button] : @options[:negative_button] # if a text_view is present, grab what the user gave us text_view = @text_view_id && dialog.findViewById(@text_view_id) input_text = text_view ? text_view.text.toString : nil @callback.call(button_text, input_text) if @callback end end
require 'test_helper' class UsersSignupTest < ActionDispatch::IntegrationTest def setup @user_data = {username: "waeiawe", email: "foo.bar@baz.qux", password: "iamatestpassword1", password_confirmation: "iamatestpassword1"} end test "valid signup information" do get signup_path assert_difference 'User.count' do post_via_redirect users_path, user: @user_data end assert_template 'users/show' end end
require './lib/atm.rb' require 'date' require 'pry-byebug' describe Atm do let(:account) { instance_double('Account', pin_code: '1234', exp_date: '04/2017', account_status: :active ) } before do allow(account).to receive(:balance).and_return(100) allow(account).to receive(:balance=) end it 'has $1000 on initialize' do expect(subject.funds).to eq(1000) end it 'funds are reduced at withdraw' do subject.withdraw(50,'1234','04/2017', :active, account) expect(subject.funds).to eq(950) end it 'allow withdraw if account has enough balance' do amount = 45 expected_output = { status: true, message: 'success', date: Date.today, amount: amount, :bills => [20,20,5] } expect(subject.withdraw(45, '1234','04/2017', :active, account)).to eq expected_output end it 'reject withdraw if account has sufficient funds' do expected_output = { status: true, message: 'insufficient funds', date: Date.today } expect(subject.withdraw(105,'1234', '04/2017', :active, account)).to eq expected_output end it 'rejects withdraw if ATM has insufficient funds' do subject.funds = 50 expected_output = { status: false, message: 'insufficient funds in ATM', date: Date.today } expect(subject.withdraw(100, '1234', '04/2017', :active, account)).to eq expected_output end it 'reject withdraw if pin is wrong' do expected_output = { status: false, message: 'wrong pin', date: Date.today } expect(subject.withdraw(50, 9999, '04/2017', :active, account)).to eq(expected_output ) end it 'rejects withdraw if card is expired' do allow(account).to receive(:exp_date).and_return('12/2015') expected_output = {status: false, message: 'card expired', date: Date.today} expect(subject.withdraw(6, '1234', '12/2015', :active, account)).to eq (expected_output) end it 'rejects withdraw if account is disabled' do allow(account).to receive(:account_status).and_return(:active) expected_output = {status: false, message: 'Account disabled', date: Date.today} expect(subject.withdraw(30, '1234', '12/2015', :disabled, account)).to eq (expected_output) end end
class FluentdUiRestartJob < ApplicationJob queue_as :default LOCK = [] def lock! raise "update process is still running" if locked? LOCK << true # dummy value end def locked? LOCK.present? end def unlock! LOCK.shift end def perform lock! # NOTE: install will be failed before released fluentd-ui gem logger.info "[restart] install new fluentd-ui" Plugin.new(gem_name: "fluentd-ui").install! if Rails.env.production? cmd = %W(#{Rails.root}/bin/fluentd-ui start) else cmd = %W(bundle exec rails s) end logger.info "[restart] will restart" Bundler.with_clean_env do restarter = "#{Rails.root}/bin/fluentd-ui-restart" Process.spawn(*[restarter, $$.to_s, *cmd, *ARGV]) && Process.kill(:TERM, $$) end ensure # don't reach here if restart is successful unlock! end end
require 'vlad' include Rake::DSL # @author Joshua P. Mervine <joshua@mervine.net> # # Please see {file:lib/vlad/push.rb Vlad::Push Source} for Rake task documentation. class Vlad::Push VERSION = "1.1.2" # @attribute[rw] # init Vlad::Push set :source, Vlad::Push.new # @attribute[rw] # set default repository set :repository, "/tmp/repo" # @attribute[rw] # set default scm set :scm, :push # @attribute[rw] # allow for overwriting release_name via command line set :release_name, ENV['RELEASE']||release_name # @attribute[rw] # set default directory to build tarballs in set :extract_dir, "/tmp" # @attribute[rw] # set default name of tarball generates, you should override this in your rakefile set :extract_file, "vlad-push-extract-#{release_name}.tgz" # Overwriting Vlad.checkout, to do nothing. # # @return [String] echo bash command # # @param revision [String] ignored # @param destination [String] ignored def checkout(revision, destination) "echo '[vlad-push] skipping checkout, not needed without scm'" end # Overwrite Vlad.export to simply copied what was # pushed from the 'repository' location to the # 'destination' # # @param source [String] ignored # @param destination [String] target export folder def export(source, destination) "cp -r #{repository} #{destination}" end # Overwriting Vlad.revision # # @param revision [String] ignored # @return [String] returning 'repository' def revision(revision) repository end # Extract the remote compressed file on each host # # @return [String] bash command to extract compressed archive on remote server def push_extract [ "if [ -e #{repository} ]; then rm -rf #{repository}; fi", "mkdir -p #{repository}", "cd #{repository}", "tar -xzf #{extract_dir}/#{extract_file}" ].join(" && ") end # Clean up old compressed archives both locally and remotely # # @return [String] bash command to remove compressed archives def push_cleanup [ "rm -vrf /tmp/#{application}-*.tgz", [ "if [ -e #{repository} ]", "then rm -rf #{repository}", "fi" ].join("; ") ].join(" && ") end # Compress the files in the current working directory # to be pushed to the remote server # # @return [String] bash command to compress current directory def compress [ "tar -czf #{extract_dir}/#{extract_file}", '--exclude "\.git*"', '--exclude "\.svn*"', "." ].join(" ") end # Using :vlad namespace to make this part # of vlad in rake namespace :vlad do desc "Built the extracted tarball to be pushed from the CWD" task :create_extract do sh source.compress end # Run the following on specified environment: # * Vlad::Push.compress # * Vlad::Push.push # * Vlad::Push.push_extract desc "Push current working directory to remote servers." remote_task :push => :create_extract do rsync "#{extract_dir}/#{extract_file}", "#{target_host}:#{extract_dir}/#{extract_file}" run source.push_extract end # Updating 'vlad:cleanup' to include post-task remote_task :cleanup do Rake::Task['vlad:push_cleanup'].invoke end # Run the following on specified environment: # * Vlad::Push.push_cleanup on local machine # * Vlad::Push.push_cleanup on remote machines desc "Clean up archive files created by push. This will also be run by vlad:cleanup." remote_task :push_cleanup do sh source.push_cleanup run source.push_cleanup end # Adding task to do both 'vlad:push' and 'vlad:update' rake tasks desc "Runs push and update" task :deploy do Rake::Task["vlad:push"].invoke Rake::Task["vlad:update"].invoke end end end
class ClubsController < ApplicationController def all @clubs = Club.all end def one @club = Club.find_by(id: params[:id]) @players = Player.where(club_id: params[:id]) @players_by_level = @players.group_by{|player| player.level} raise ActionController::RoutingError.new('Not Found') if @club.nil? end def show_image @club = Club.find_by(id: params[:id]) if @club.symbol.nil? send_file 'app/assets/images/default.png' else send_data @club.symbol end end end
class Registration < ApplicationRecord belongs_to :user, :optional => true belongs_to :event end
require 'rails_helper' describe 'company contacts' do scenario 'user can see a field for contact input on company page' do company = Company.create!(name: "Evil Industries") category = Category.create!(title: "World Domination") job = Job.create!(title: "Henchman 1", description: "Disposable Meat", level_of_interest: 75, city: "New New York", category_id: category.id, company_id: company.id ) job_2 = Job.create!(title: "Henchman 2", description: "Disposable Meat", level_of_interest: 70, city: "New New York", category_id: category.id, company_id: company.id ) visit company_path(company) fill_in("Name", :with => "Viktor") fill_in("Email", :with => "Viktor@gmail.com") fill_in("Position", :with => "Stabber") click_on("Create Contact") expect(current_path).to eq(company_path(company)) expect(page).to have_content("Viktor@gmail.com") expect(page).to have_content("Viktor") expect(page).to have_content("Stabber") end end
require 'pry' class Node class EmptyNode < Node def initialize @value = nil end end attr_accessor :value, :next_node def initialize(initial) @value = initial @next_node = EmptyNode.new end def to_s string = "#{value}\n" string += next_node.to_s unless tail? string end def find(val) !tail? && @value == val ? true : next_node.find(val) end def nth_value(n) raise ArgumentError, "Index not found" if n < 0 n == 0 ? value : next_node.nth_value(n - 1) end def push(new_value) tail? ? @next_node = Node.new(new_value) : next_node.push(new_value) end def pop if tail? EmptyNode.new elsif penultimate? old_node = next_node @next_node = EmptyNode.new else next_node.pop end end def reverse(previous = nil) if tail? next_node = previous || self else next_node = previous || self next_node.reverse(self) end end def shift(new_value) new_node = Node.new(new_value).tap {|new_node| new_node.next_node = self } end def unshift next_node end def length tail? ? 1 : (1 + next_node.length) end def penultimate? next_node.tail? end def tail? next_node.is_a?(EmptyNode) end end
require 'spec_helper' require 'lib' module Prct06 class Libro describe Prct06::Libro do before :each do @libro = Libro.new "autor","titulo","editorial", "edicion", "fecha", :isbn end describe "#new" do it "Introduce parametros y retorna un objeto tipo Libro" do @Libro.should be_an_instance_of Libro end end describe "#autor" do it "Retorna el autor del libro" do @libro.autor.should eql "autor" end end describe "#titulo" do it "Retorna el titulo del libro" do @libro.titulo.should eql "titulo" end end describe "#editorial" do it "Retorna la editorial del libro" do @libro.editorial.should eql "editorial" end end describe "#edicion" do it "Retorna la edicion del libro" do @libro.edicion.should eql "edicion" end end describe "#fecha" do it "Retorna la fecha del libro" do @libro.fecha.should eql "fecha" end end describe "#isbn" do it "Retorna el isbn del libro" do @libro.isbn.should eql :isbn end end end end end
class Post < ActiveRecord::Base has_many :comments belongs_to :user default_scope { order('created_at DESC') } scope :ordered_by_title, -> { reorder(title: :asc) } scope :ordered_by_reverse_created_at, -> { reorder('created_at DESC') } end
class AddSubContentToIdeas < ActiveRecord::Migration[5.2] def change add_column :ideas, :sub_content, :string end end
cookbook_file "/etc/prometheus/alertmanager.yml" do owner "prometheus" group "prometheus" end prometheus_alertmanager "Test Kitchen" do action :create version '0.20.0' uri 'https://github.com/prometheus/alertmanager/releases/download/v0.20.0/alertmanager-0.20.0.linux-amd64.tar.gz' checksum '3a826321ee90a5071abf7ba199ac86f77887b7a4daa8761400310b4191ab2819' filename 'alertmanager-0.20.0.linux-amd64.tar.gz' pathname 'alertmanager-0.20.0.linux-amd64' end
# comment require_relative 'wagon' class CargoWagon < Wagon def initialize(name, volume) super('cargo', name) @volume = volume @reserved_space = 0 validate! end attr_reader :reserved_space, :volume def reserve_space(value) raise 'превышен объем вагона' if reserved_volume + value > volume @reserved_space += value end def free_space volume - reserved_space end private attr_writer :reserved_space end
# frozen_string_literal: true require 'sinatra' require 'discordrb' require 'json' module RubotHandlers; end $handlers = {} # Method to load handlers def deploy! # Load all the module code files. Dir.glob('handlers/*.rb') { |mod| load mod } RubotHandlers.constants.each do |name| const = RubotHandlers.const_get name if const.is_a? Module $handlers[name.to_s.downcase] = const end end end deploy! # Read the file of existing links so we don't have to re-add everything all the time $links = JSON.parse(File.read('rubot-links')) token, app_id = File.read('rubot-auth').lines bot = Discordrb::Bot.new token: token, application_id: app_id.to_i puts bot.invite_url bot.message(starting_with: 'rubot, link this:') do |event| name = event.content.split(':')[1].strip $links[name] ||= [] $links[name] << event.channel.id File.write('rubot-links', $links.to_json) event.respond "Linked repo #{name} to #{event.channel.mention} (`#{event.channel.id}`)" end bot.message(starting_with: 'rubot, reload handlers') do |event| deploy! event.respond("Loaded #{$handlers.length} handlers") end bot.message(starting_with: 'rubot, eval:') do |event| if event.user.id == 66237334693085184 # Replace this ID with yours if you want to do eval _, *stuff = event.content.split(':') event.respond(eval(stuff.join(':'))) else event.respond('To quote the great Hlaaftana: *You cannot use this command. Want to know why? This command evaluates actual Groovy code, giving you access to my entire computer file system and networking. You could delete system32, download gigabytes of illegal porn and delete all my files. If you think this is unfair, write your own bot, idiot.* Now this is not 100% correct, as the command evaluates Ruby code, not Groovy, and runs on Linux without a system32 folder, but you get the gist of it.') end end bot.run :async class WSPayload attr_reader :data def initialize(payload) @data = payload end def repo_name @data['repository']['full_name'] end def sender_name @data['sender']['login'] end def issue @data['issue'] end def pull_request @data['pull_request'] end def tiny_issue "**##{issue['number']}** (" + %(**#{issue['title']}**) + issue['labels'].map { |e| " `[#{e['name']}]`"}.join + ')' end def tiny_pull_request "**##{pull_request['number']}** (" + %(**#{pull_request['title']}**) + ')' end def action @data['action'] end def [](key) @data[key] end end def handle(event_type, payload) event_type = event_type.delete('_') payload = WSPayload.new(payload) if $handlers[event_type] $handlers[event_type].handle(payload) else nil end end get '/webhook' do "Hooray! The bot works. #{$links.length} links are currently registered." end post '/webhook' do request.body.rewind event_type = request.env['HTTP_X_GITHUB_EVENT'] # The event type is a custom request header payload = JSON.parse(request.body.read) repo_name = payload['repository']['full_name'] channels = $links[repo_name] channels.each do |e| response = handle(event_type, payload) if response bot.send_message(e, "**#{repo_name}**: **#{payload['sender']['login']}** " + response) else puts %(Got a "#{event_type}" event for repo #{repo_name} that is not supported - ignoring) end end 204 end
require 'pry' =begin // --- Directions // Write a function that returns the number of vowels // used in a string. Vowels are the characters 'a', 'e' // 'i', 'o', and 'u'. // --- Examples // vowels('Hi There!') --> 3 // vowels('Why do you ask?') --> 4 // vowels('Why?') --> 0 =end module Vowels VOWELS = %w[a e i o u] def self. num_vowels(str) count = 0 str.each_char do |ch| count+=1 if VOWELS.include? ch end count end end
action :create do user 'prometheus' do system true shell '/bin/false' home new_resource.home_dir end directory new_resource.home_dir do action :create recursive true mode 0755 owner 'prometheus' group 'prometheus' end directory new_resource.home_dir + '/bin' do action :create recursive true mode 0755 owner 'prometheus' group 'prometheus' end remote_file Chef::Config[:file_cache_path] + '/' + new_resource.filename do source new_resource.uri checksum new_resource.checksum action :create_if_missing end execute 'extract ' + new_resource.name do cwd Chef::Config[:file_cache_path] command 'tar zxf ' + new_resource.filename creates Chef::Config[:file_cache_path] + '/' + new_resource.pathname + '/README.md' end raise 'binaries array is unset cannot proceed' if new_resource.binaries.empty? new_resource.binaries.each do |p| execute 'install ' + p do cwd Chef::Config[:file_cache_path] + '/' + new_resource.pathname command 'cp ' + p + ' ' + new_resource.home_dir + '/bin' creates '/opt/prometheus/bin/' + p end end template '/etc/default/prometheus-' + new_resource.name do source new_resource.template_name cookbook new_resource.cookbook owner 'prometheus' group 'prometheus' variables( args: new_resource.arguments, dsn: new_resource.dsn ) end raise 'no start_command given' unless new_resource.start_command systemd_service 'prometheus-' + new_resource.name do unit do description new_resource.name after %w( networking.service ) end install do wanted_by %w( multi-user.target ) end service do type 'simple' user 'prometheus' group 'prometheus' exec_start new_resource.home_dir + '/bin/' + new_resource.start_command + ' $ARGS' exec_reload '/bin/kill -HUP $MAINPID' service_environment_file '/etc/default/prometheus-' + new_resource.name timeout_stop_sec '20s' # verify false end end service 'prometheus-' + new_resource.name do action [:start, :enable] provider Chef::Provider::Service::Systemd subscribes :restart, 'template[/etc/default/prometheus-' + new_resource.name + ']', :delayed end end
Puppet::Type.newtype(:f5_node) do @doc = "Manage F5 node." apply_to_device ensurable do defaultvalues defaultto :present end newparam(:name, :namevar=>true) do desc "The node name." validate do |value| unless Puppet::Util.absolute_path?(value) fail Puppet::Error, "Node names must be fully qualified, not '#{value}'" end end end newproperty(:connection_limit) do desc "The connection limit of the node." munge do |value| begin Integer(value) rescue fail Puppet::Error, "'connection_limit' must be a number, not '#{value}'" end end end newproperty(:description) do desc "The description of the node." end newproperty(:dynamic_ratio) do desc "The dynamic ratio of the node." munge do |value| begin Integer(value) rescue fail Puppet::Error, "'dynamic_ratio' must be a number, not '#{value}'" end end end newparam(:ipaddress) do desc "The ip address of the node" end newproperty(:health_monitors, :array_matching => :all) do desc "The health monitors of the node. Specify the special value 'none' to disable all monitors. e.g.: ['/Common/icmp'. '/Common/http']" def should_to_s(newvalue) newvalue.inspect end # Override the default method because it assumes there is nothing to do if @should is empty def insync?(is) is.sort == @should.sort end validate do |value| unless Puppet::Util.absolute_path?(value) || value == "none" || value == "default" fail Puppet::Error, "Health monitors must be fully qualified (e.g. '/Common/http'), not '#{value}'" end end end newproperty(:rate_limit) do desc "The rate_limit of the node." munge do |value| begin Integer(value) rescue fail Puppet::Error, "'rate_limit' must be a number, not '#{value}'" end end end newproperty(:ratio) do desc "The ratio of the node." munge do |value| begin Integer(value) rescue fail Puppet::Error, "'ratio' must be a number, not '#{value}'" end end end newproperty(:session_status) do desc "The states that allows new sessions to be established for the specified node addresses." munge do |value| value.upcase end validate do |value| unless /^(DISABLED|ENABLED)$/i.match(value) fail Puppet::Error, "session_status must be either disabled or enabled, not #{value}" end end end ########################################################################### # Parameters used at creation. ########################################################################### # These attributes are parameters because, often, we want objects to be # *created* with property values X, but still let a human make changes # to them without puppet getting in the way. newparam(:atcreate_connection_limit) do desc "The connection limit of the node at creation." munge do |value| begin Integer(value) rescue fail Puppet::Error, "'atcreate_connection_limit' must be a number, not '#{value}'" end end defaultto 0 # unlimited end newparam(:atcreate_description) do desc "The description of the node at creation." end newparam(:atcreate_dynamic_ratio) do desc "The dynamic ratio of the node at creation." munge do |value| begin Integer(value) rescue fail Puppet::Error, "'atcreate_dynamic_ratio' must be a number, not '#{value}'" end end end newparam(:atcreate_health_monitors) do desc "The health monitors of the node at creation. Specify the special value 'none' to disable all monitors. e.g.: ['/Common/icmp'. '/Common/http']" validate do |value| value = [value] unless value.is_a?(Array) value.each do |item| unless Puppet::Util.absolute_path?(item) || item == "none" || item == "default" fail Puppet::Error, "'atcreate_health_monitors' must be fully"\ "qualified (e.g. '/Common/http'), not '#{item}'" end end end end newparam(:atcreate_rate_limit) do desc "The rate_limit for the node at creation." munge do |value| begin Integer(value) rescue fail Puppet::Error, "'atcreate_rate_limit' must be a number, not '#{value}'" end end end newparam(:atcreate_ratio) do desc "The ratio of the node at creation." munge do |value| begin Integer(value) rescue fail Puppet::Error, "'atcreate_port' must be a number, not '#{value}'" end end end newparam(:atcreate_session_status) do desc "The states that allows new sessions to be established for the specified node addresses at creation." munge do |value| value.upcase end validate do |value| unless /^(DISABLED|ENABLED)$/i.match(value) fail Puppet::Error, "atcreate_session_status must be either disabled or enabled, not '#{value}'" end end end ########################################################################### # Validation ########################################################################### autorequire(:f5_partition) do File.dirname(self[:name]) end autorequire(:f5_monitor) do self[:health_monitors] end end
require "pry" class Guest attr_reader :name @@all = [] def initialize(name) @name = name @@all << self end def listings #array of all listings guest has stayed at Trip.all.select do |trip| trip.guest == self end end def trips Trip.all.select{|trip|trip.guest == self} end def trips_count self.trips.count end def self.all @@all end def self.find_all_by_name(name) self.all.select{|guest|guest.name == self.name} end def self.pro_traveller self.all.select{|guest|guest.trips_count > 1} end def self.find_all_by_name(name) self.all.select{|guest|guest.name == name} end end
helpers do def get_bib_entry(bib_key) bib_hash = {} entry = $bib[bib_key] # Paper or talk title, minus the {forced capitalization} required for bibtex bib_hash[:title] = entry.title.delete "{}" # Stacked list of authors separated by linebreaks bib_hash[:authors] = entry.author.length == 1 ? entry.author.to_s : ( entry.author.to_s.gsub! ' and ', '<br/>' ) bib_hash[:authors].gsub! 'Dickerson, John P.', '<strong>Dickerson, John P.</strong>' # Is this a first author publication? bib_hash[:first_author] = entry.author[0].last == "Dickerson" # Publication or talk year bib_hash[:year] = entry.type == :unpublished ? "Working" : entry.year # :venue will map to a booktitle or bib_hash[:venue] = "" if not entry.booktitle.nil? then # conference bib_hash[:venue] += entry.booktitle.to_s elsif not entry.journal.nil? then # journal bib_hash[:venue] += entry.journal.to_s elsif not entry.publisher.nil? then # book bib_hash[:venue] += entry.publisher.to_s end if not entry.note.nil? then bib_hash[:venue] += (bib_hash[:venue].empty? ? "" : ". ") + entry.note.to_s end bib_hash[:venue].delete! "{}" # Absolute filepath to pdf link (MAY NOT EXIST, check elsewhere) bibkey_link = bib_key_to_link(bib_key) bib_hash[:pdfpath] = "/pubs/#{bibkey_link}.pdf" bib_hash[:pdflink] = "<a id=\"#{bibkey_link}\" href=\"/pubs/#{bibkey_link}.pdf\">pdf</a>" # Google Analytics click tracking bib_hash[:ga_track] = "<script type='text/javascript'>" + ga_event_tracking(bibkey_link, "/pubs/#{bibkey_link}.pdf") + "</script>" return bib_hash end # Takes an array of string keys into a .bib file and returns an HTML # list of their citations, formatted via cite_to_link def rep_pubs_list(bib_keys, include_links=false) bibkey_links = Array.new out = "<ul class='list-unstyled'>" out += bib_keys.uniq.map do |bib_key| bibkey_link = bib_key_to_link(bib_key) bibkey_links << bibkey_link # track links for GA code later "<li><span class='glyphicon glyphicon-chevron-right'></span> #{cite_to_link($bib[bib_key])} " + ((include_links == true) ? "[<a id=\"#{bibkey_link}\" href=\"/pubs/#{bibkey_link}.pdf\">link</a>]" : "") + "</li>" end.join out += "</ul>\n" # Include Google Analytics click tracking out += "<script type='text/javascript'>" bibkey_links.each{ |bibkey_link| out += ga_event_tracking(bibkey_link, "/pubs/#{bibkey_link}.pdf") + "\n" } out += "</script>" end # Google Analytics event tracking via JQuery def ga_event_tracking(element_name, desc) return "$('\##{element_name}').on('click', function() {ga('send', 'event', 'button', 'click', '#{desc}');});" end # Processes a bibtex entry into a human-readable string, and removes all {s and }s. def cite_to_link(bib_struct) base = (CiteProc.process bib_struct.to_citeproc, :style => $bib_citestyle, :format => :html).delete "{}" # MLA style displays "Print." after some entries, and that's dumb. Remove it base.chomp!("Print.") # Can't figure out how to display note field in bibtex, so force it in if not bib_struct[:note].nil? then base += " " + (bib_struct[:note].delete "{}") end return base end # Translate a bib_key that looks like "NameYear:Title" into a URL def bib_key_to_link(bib_key) bib_key.downcase.delete(':') end end
require 'rails_helper' RSpec.describe WfsRails::WorkflowParser do include XmlFixtures let(:druid) { 'druid:abc123' } let(:repository) { 'dor' } let(:wf_parser) { described_class.new(workflow_create, druid, repository) } describe '#create_workflows' do it 'creates a workflow for each process' do expect do wf_parser.create_workflows end.to change(WfsRails::Workflow, :count) .by(Nokogiri::XML(workflow_create).xpath('//process').count) expect(WfsRails::Workflow.last.druid).to eq druid expect(WfsRails::Workflow.last.repository).to eq repository end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |gem| gem.name = "imdb-party" gem.version = "1.1" gem.authors = ["John Maddox", "Mike Mesicek"] gem.email = ["jon@mustacheinc.com"] gem.description = %q{Imdb JSON client used IMDB to serve information to the IMDB iPhone app via the IMDB API} gem.summary = "IMDB API for Rails" gem.homepage = 'https://github.com/mastermike14/imdb-party' gem.license = "MIT" gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}) { |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] if File.exists?('UPGRADING') gem.post_install_message = File.read('UPGRADING') end gem.add_runtime_dependency 'rails', ['>= 4', '< 6'] gem.add_development_dependency 'rspec-rails', '2.13.0' # 2.13.1 is broken gem.add_development_dependency 'rspec', '~> 2.6' gem.add_development_dependency 'shoulda' gem.add_development_dependency 'httparty' gem.add_development_dependency 'hpricot' gem.add_development_dependency 'guard' gem.add_development_dependency 'guard-rspec' end
class CreateDeals < ActiveRecord::Migration def change create_table :deals do |t| t.integer :deal_id t.string :user_name t.integer :category t.binary :photo1 t.binary :photo2 t.binary :photo3 t.binary :photo4 t.string :title t.text :explanation t.timestamps null: false end end end
require 'machinist/active_record' # Best Practices: #- Keep blueprints minimal #- If you want to construct a whole graph of connected objects, do it outside of a blueprint #- Sort your blueprints alphabetically AdditionalCost.blueprint do user name {"name_#{sn}"} cost_monthly_baseline {10} end Application.blueprint do user deployment server name {"name_#{sn}"} instance_hour_monthly_baseline {10} end Cloud.blueprint do cloud_provider name {"name_#{sn}"} billing_currency {"USD"} location {"United States"} end CloudCostScheme.blueprint do cloud cloud_resource_type {Server.make} cloud_cost_structure end CloudCostStructure.blueprint do name {"instance_hour"} units {"per.1.hours"} end CloudCostTier.blueprint do cloud_cost_structure name {"name_#{sn}"} upto {100} cost {0.2} end CloudProvider.blueprint do name {"name_#{sn}"} end DatabaseResource.blueprint do user deployment database_type cloud name {"name_#{sn}"} storage_size_monthly_baseline {10} instance_hour_monthly_baseline {10} transaction_monthly_baseline {10} quantity_monthly_baseline {1} end DatabaseType.blueprint do name {"On Demand Standard Small"} cpu_architecture {"X64"} cpu_speed {1.0} cpu_count {1} memory {1.7} software {"MySQL"} end DataChunk.blueprint do user deployment storage name {"name_#{sn}"} storage_size_monthly_baseline {10} read_request_monthly_baseline {10} write_request_monthly_baseline {10} end DataLink.blueprint do user deployment sourcable {Application.make} targetable {DataChunk.make} source_to_target_monthly_baseline {5} target_to_source_monthly_baseline {10} end Deployment.blueprint do user name {"name_#{sn}"} end Pattern.blueprint do user name {"name_#{sn}"} end PatternMap.blueprint do user patternable {Application.make} patternable_attribute {"instance_hour_monthly_baseline"} pattern end Report.blueprint do user name {"name_#{sn}"} reportable {Deployment.make} start_date {"2012-01-01"} end_date {"2013-01-01"} end RemoteNode.blueprint do user deployment name {"name_#{sn}"} end Rule.blueprint do user pattern rule_type {"permanent"} year {"every.1.years"} month {"every.1.months"} day {"every.1.days"} hour {"every.1.hours"} variation {"+"} value {"1"} end Server.blueprint do user deployment server_type cloud name {"name_#{sn}"} instance_hour_monthly_baseline {10} quantity_monthly_baseline {1} end ServerType.blueprint do name {"On Demand Standard Small"} cpu_architecture {"X86"} cpu_speed {1.0} cpu_count {1} local_disk_count {1} local_disk_size {160} memory {1.7} operating_system {"Linux"} end Storage.blueprint do user deployment storage_type cloud name {"name_#{sn}"} storage_size_monthly_baseline {10} read_request_monthly_baseline {10} write_request_monthly_baseline {10} quantity_monthly_baseline {1} end StorageType.blueprint do name {"S3"} end User.blueprint do email {"email_#{rand(2**32)}@shopforcloud.com"} password {"password"} password_confirmation {"password"} first_name {"first_name_#{sn}"} last_name {"last_name_#{sn}"} company {"company_#{sn}"} end Service.blueprint do user name {"service_name_#{sn}"} end Service.blueprint(:include_associations) do user name {"service_name_#{sn}"} service_features {[ServiceFeature.make(:user => object.user)]} service_pricing_schemes {[ServicePricingScheme.make(:charge_by_user, :user => object.user)]} service_demands {[ServiceDemand.make(:user => object.user)]} end Service.blueprint(:with_new_charging_resource_type) do user name {"service_name_#{sn}"} service_features {[ServiceFeature.make(:user => object.user)]} service_pricing_schemes {[ServicePricingScheme.make(:user => object.user)]} service_demands {[ServiceDemand.make(:user => object.user)]} end ServiceDemand.blueprint do user name {"service_demand_name_#{sn}"} customer_type {CustomerType.make(:user => object.user)} customer_quantity_baseline {rand(1000)} end ServiceFeature.blueprint do user name {"service_feature_name_#{UUIDTools::UUID.timestamp_create}"} end ServicePricingScheme.blueprint do user unit_cost {rand(1000)} charging_unit {rand(1000)} service_charging_resource_type {ServiceChargingResourceType.make(:user => object.user)} end ServicePricingScheme.blueprint(:charge_by_user) do user unit_cost {rand(1000)} charging_unit {rand(10000)} service_charging_resource_type { object.user.service_charging_resource_types.where("name = 'User'").first } end ServicePricingScheme.blueprint(:charge_by_time) do user unit_cost {rand(1000)} charging_unit {rand(24*365*5)} service_charging_resource_type { object.user.service_charging_resource_types.where("name like 'Usage Time%'")} end ServicePricingScheme.blueprint(:charge_by_storage) do user unit_cost {rand(1000)} charging_unit {rand(1000**3)} service_charging_resource_type { object.user.service_charging_resource_types.where("name like 'Storage%'")} end ServiceChargingResourceType.blueprint do user name {"service_charging_resource_type_#{sn}"} end CustomerType.blueprint do user name {"customer_type_#{sn}"} end
class FamilySerializer < ActiveModel::Serializer attributes :id, :family_name, :posts, :users has_many :posts end
require "spec_helper" describe Paperclip::Interpolations do it "returns all methods but the infrastructure when sent #all" do methods = Paperclip::Interpolations.all assert !methods.include?(:[]) assert !methods.include?(:[]=) assert !methods.include?(:all) methods.each do |m| assert Paperclip::Interpolations.respond_to?(m) end end it "returns the Rails.root" do assert_equal Rails.root, Paperclip::Interpolations.rails_root(:attachment, :style) end it "returns the Rails.env" do assert_equal Rails.env, Paperclip::Interpolations.rails_env(:attachment, :style) end it "returns the class of the Interpolations module when called with no params" do assert_equal Module, Paperclip::Interpolations.class end it "returns the class of the instance" do class Thing; end attachment = spy expect(attachment).to receive(:instance).and_return(attachment) expect(attachment).to receive(:class).and_return(Thing) assert_equal "things", Paperclip::Interpolations.class(attachment, :style) end it "returns the basename of the file" do attachment = spy expect(attachment).to receive(:original_filename).and_return("one.jpg") assert_equal "one", Paperclip::Interpolations.basename(attachment, :style) end it "returns the extension of the file" do attachment = spy expect(attachment).to receive(:original_filename).and_return("one.jpg") expect(attachment).to receive(:styles).and_return({}) assert_equal "jpg", Paperclip::Interpolations.extension(attachment, :style) end it "returns the extension of the file as the format if defined in the style" do attachment = spy expect(attachment).to_not receive(:original_filename) expect(attachment).to receive(:styles).at_least(2).times.and_return(style: { format: "png" }) [:style, "style"].each do |style| assert_equal "png", Paperclip::Interpolations.extension(attachment, style) end end it "returns the extension of the file based on the content type" do attachment = spy expect(attachment).to receive(:content_type).and_return("image/png") expect(attachment).to receive(:styles).and_return({}) interpolations = Paperclip::Interpolations expect(interpolations).to receive(:extension).and_return("random") assert_equal "png", interpolations.content_type_extension(attachment, :style) end it "returns the original extension of the file if it matches a content type extension" do attachment = spy expect(attachment).to receive(:content_type).and_return("image/jpeg") expect(attachment).to receive(:styles).and_return({}) interpolations = Paperclip::Interpolations expect(interpolations).to receive(:extension).and_return("jpe") assert_equal "jpe", interpolations.content_type_extension(attachment, :style) end it "returns the extension of the file with a dot" do attachment = spy expect(attachment).to receive(:original_filename).and_return("one.jpg") expect(attachment).to receive(:styles).and_return({}) assert_equal ".jpg", Paperclip::Interpolations.dotextension(attachment, :style) end it "returns the extension of the file without a dot if the extension is empty" do attachment = spy expect(attachment).to receive(:original_filename).and_return("one") expect(attachment).to receive(:styles).and_return({}) assert_equal "", Paperclip::Interpolations.dotextension(attachment, :style) end it "returns the latter half of the content type of the extension if no match found" do attachment = spy allow(attachment).to receive(:content_type).at_least(1).times.and_return("not/found") allow(attachment).to receive(:styles).and_return({}) interpolations = Paperclip::Interpolations expect(interpolations).to receive(:extension).and_return("random") assert_equal "found", interpolations.content_type_extension(attachment, :style) end it "returns the format if defined in the style, ignoring the content type" do attachment = spy expect(attachment).to receive(:content_type).and_return("image/jpeg") expect(attachment).to receive(:styles).and_return(style: { format: "png" }) interpolations = Paperclip::Interpolations expect(interpolations).to receive(:extension).and_return("random") assert_equal "png", interpolations.content_type_extension(attachment, :style) end it "is able to handle numeric style names" do attachment = spy( styles: {:"4" => {format: :expected_extension}} ) assert_equal :expected_extension, Paperclip::Interpolations.extension(attachment, 4) end it "returns the #to_param of the attachment" do attachment = spy expect(attachment).to receive(:to_param).and_return("23-awesome") expect(attachment).to receive(:instance).and_return(attachment) assert_equal "23-awesome", Paperclip::Interpolations.param(attachment, :style) end it "returns the id of the attachment" do attachment = spy expect(attachment).to receive(:id).and_return(23) expect(attachment).to receive(:instance).and_return(attachment) assert_equal 23, Paperclip::Interpolations.id(attachment, :style) end it "returns nil for attachments to new records" do attachment = spy expect(attachment).to receive(:id).and_return(nil) expect(attachment).to receive(:instance).and_return(attachment) assert_nil Paperclip::Interpolations.id(attachment, :style) end it "returns the partitioned id of the attachment when the id is an integer" do attachment = spy expect(attachment).to receive(:id).and_return(23) expect(attachment).to receive(:instance).and_return(attachment) assert_equal "000/000/023", Paperclip::Interpolations.id_partition(attachment, :style) end it "returns the partitioned id when the id is above 999_999_999" do attachment = spy expect(attachment).to receive(:id).and_return(Paperclip::Interpolations::ID_PARTITION_LIMIT) expect(attachment).to receive(:instance).and_return(attachment) assert_equal "001/000/000/000", Paperclip::Interpolations.id_partition(attachment, :style) end it "returns the partitioned id of the attachment when the id is a string" do attachment = spy expect(attachment).to receive(:id).and_return("32fnj23oio2f") expect(attachment).to receive(:instance).and_return(attachment) assert_equal "32f/nj2/3oi", Paperclip::Interpolations.id_partition(attachment, :style) end it "returns nil for the partitioned id of an attachment to a new record (when the id is nil)" do attachment = spy expect(attachment).to receive(:id).and_return(nil) expect(attachment).to receive(:instance).and_return(attachment) assert_nil Paperclip::Interpolations.id_partition(attachment, :style) end it "returns the name of the attachment" do attachment = spy expect(attachment).to receive(:name).and_return("file") assert_equal "files", Paperclip::Interpolations.attachment(attachment, :style) end it "returns the style" do assert_equal :style, Paperclip::Interpolations.style(:attachment, :style) end it "returns the default style" do attachment = spy expect(attachment).to receive(:default_style).and_return(:default_style) assert_equal :default_style, Paperclip::Interpolations.style(attachment, nil) end it "reinterpolates :url" do attachment = spy expect(attachment).to receive(:url).with(:style, timestamp: false, escape: false).and_return("1234") assert_equal "1234", Paperclip::Interpolations.url(attachment, :style) end it "raises if infinite loop detcted reinterpolating :url" do attachment = Object.new class << attachment def url(*_args) Paperclip::Interpolations.url(self, :style) end end assert_raises(Paperclip::Errors::InfiniteInterpolationError) { Paperclip::Interpolations.url(attachment, :style) } end it "returns the filename as basename.extension" do attachment = spy expect(attachment).to receive(:styles).and_return({}) expect(attachment).to receive(:original_filename).and_return("one.jpg").twice assert_equal "one.jpg", Paperclip::Interpolations.filename(attachment, :style) end it "returns the filename as basename.extension when format supplied" do attachment = spy expect(attachment).to receive(:styles).and_return(style: { format: :png }) expect(attachment).to receive(:original_filename).and_return("one.jpg").once assert_equal "one.png", Paperclip::Interpolations.filename(attachment, :style) end it "returns the filename as basename when extension is blank" do attachment = spy allow(attachment).to receive(:styles).and_return({}) allow(attachment).to receive(:original_filename).and_return("one") assert_equal "one", Paperclip::Interpolations.filename(attachment, :style) end it "returns the basename when the extension contains regexp special characters" do attachment = spy allow(attachment).to receive(:styles).and_return({}) allow(attachment).to receive(:original_filename).and_return("one.ab)") assert_equal "one", Paperclip::Interpolations.basename(attachment, :style) end it "returns the timestamp" do now = Time.now zone = "UTC" attachment = spy expect(attachment).to receive(:instance_read).with(:updated_at).and_return(now) expect(attachment).to receive(:time_zone).and_return(zone) assert_equal now.in_time_zone(zone).to_s, Paperclip::Interpolations.timestamp(attachment, :style) end it "returns updated_at" do attachment = spy seconds_since_epoch = 1234567890 expect(attachment).to receive(:updated_at).and_return(seconds_since_epoch) assert_equal seconds_since_epoch, Paperclip::Interpolations.updated_at(attachment, :style) end it "returns attachment's hash when passing both arguments" do attachment = spy fake_hash = "a_wicked_secure_hash" expect(attachment).to receive(:hash_key).and_return(fake_hash) assert_equal fake_hash, Paperclip::Interpolations.hash(attachment, :style) end it "returns Object#hash when passing no argument" do attachment = spy fake_hash = "a_wicked_secure_hash" expect(attachment).to_not receive(:hash_key) assert_not_equal fake_hash, Paperclip::Interpolations.hash end it "calls all expected interpolations with the given arguments" do expect(Paperclip::Interpolations).to receive(:id).with(:attachment, :style).and_return(1234) expect(Paperclip::Interpolations).to receive(:attachment).with(:attachment, :style).and_return("attachments") expect(Paperclip::Interpolations).to_not receive(:notreal) value = Paperclip::Interpolations.interpolate(":notreal/:id/:attachment", :attachment, :style) assert_equal ":notreal/1234/attachments", value end it "handles question marks" do Paperclip.interpolates :foo? do "bar" end expect(Paperclip::Interpolations).to_not receive(:fool) value = Paperclip::Interpolations.interpolate(":fo/:foo?") assert_equal ":fo/bar", value end end
# frozen_string_literal: true require 'digest' module Uploadcare module Param module Upload # This class generates signatures for protected uploads class SignatureGenerator # @see https://uploadcare.com/docs/api_reference/upload/signed_uploads/ # @return [Hash] signature and its expiration time def self.call expires_at = Time.now.to_i + Uploadcare.config.upload_signature_lifetime to_sign = Uploadcare.config.secret_key + expires_at.to_s signature = Digest::MD5.hexdigest(to_sign) { signature: signature, expire: expires_at } end end end end end
class BillDetailsController < ApplicationController before_action :set_bill_detail, only: [:show, :update, :destroy] # GET /bill_details def index @bill_details = BillDetail.all render json: @bill_details end # GET /bill_details/1 def show render json: @bill_detail end # POST /bill_details def create @bill_detail = BillDetail.new(bill_detail_params) if @bill_detail.save render json: @bill_detail, status: :created, location: @bill_detail else render json: @bill_detail.errors, status: :unprocessable_entity end end # PATCH/PUT /bill_details/1 def update if @bill_detail.update(bill_detail_params) render json: @bill_detail else render json: @bill_detail.errors, status: :unprocessable_entity end end # DELETE /bill_details/1 def destroy @bill_detail.destroy end private # Use callbacks to share common setup or constraints between actions. def set_bill_detail @bill_detail = BillDetail.find(params[:id]) end # Only allow a trusted parameter "white list" through. def bill_detail_params params.require(:bill_detail).permit(:bill_no, :bill_item_id, :bill_item_quantity, :bill_item_rate, :bill_item_amount, :bill_item_discount) end end
#DINAMICOS require "byebug" #LAMBDA #NÃO ACEITA MAIS PARAMETROS DO QUE OS DEFINIDOS #EX: 1 l = lambda do |p| #|p| funciona como uma passagem de parametro puts p end l.call("Alexandre") puts "\n" #EX: 2 l2 = lambda do |p1, p2| puts p1+p2 end l2.call(4, 5) puts "\n" #PROC #CAPTURA OS PARAMETROS POR ARGS, POSSO PASSAR VARIOS PARAMETROS #EX:1 b = Proc.new do |p,t| # |p| funciona como uma passagem de parametro puts p + " " + t end b.call("Alexandre", "Gonçalves") #EX: 2 b1 = Proc.new do |param| param = 0 if param.nil? #SE EU NAO SETAR O PARAMETRO ELE ENTRA NA MULTIPLICAÇÃO COMO NIL, GERANDO ERR param * 4 end puts b1.call(4) #EX: 3 b2 = Proc.new do |param, param2, param3| puts param puts param2 puts param3 end puts b2.call("O primeiro tem valor, os outros são NIL") #Blocos #Varios argumentos def metodo(*bloco) #debugger bloco end metodo(1,2,3,4,5) #O & utiliza um metodo para passar um bloco para uma variavel def metodo_para_definir_bloco(&bloco) bloco end h = metodo_para_definir_bloco do |param| param * 5 end puts h.call(100) # metodo do # puts "Metodo em blocos" # end.call #EVAL (TRANSFORMA ) eval(" puts '123 \n' ") atr = "nome" eval(" def #{atr}(value) @#{atr} = value end ") eval(" def mostrar @#{atr} end ") #debugger nome('Alexandre') puts mostrar #DEFININDO METODOS DINAMICOS class Teste def inicio def fim end end end t = Teste.new #debugger #t.fim #VAI DAR PAU, O METODO INICIO CRIA O FIM t.inicio t.fim #MUUUUUITO LEGAL ISSO (CRIAR METODOS EM RUNTIME) class Teste def self.definir(valor) define_method(valor) do |param1, param2| puts "#{param1} - #{param2}" #MESMA COISA DISSO: # def metodo(param1, param2) # puts "#{param1} - #{param2}" # end end def self.atributo(valor) define_method(valor) do |param1| puts "#{param1} " end end end end Teste.definir("novo_metodo") #debugger Teste.new.novo_metodo("Alexandre", "Gonçalves") Teste.definir("novo_metodo2") Teste.new.novo_metodo2("Isso é ", "muito legal cara") ['set_nome', 'set_endereco', 'set_telefone'].each do | atr| Teste.atributo(atr) end teste = Teste.new teste.set_nome ("Alexandre") teste.set_endereco("SMPW Quadra 17 COnjunto 10 Lote 08") teste.set_telefone ("55 61 9 9802-0868") #CRIANDO UM ATTR_ACCESSOR NA MÃO module AtributosDinamicos def atributos(*atrs) atrs.each do |atr| define_method("#{atr}=") do |value| instance_variable_set "@#{atr}", value end define_method("#{atr}") do instance_variable_get "@#{atr}" end end end end class Teste extend AtributosDinamicos atributos :nome, :telefone #attr_accessor :nome, :telefone end debugger t = Teste.new t.nome = "Alex" t.telefone = "999999999" puts "#{t.nome} --- #{t.telefone}"
module DublinBikes class Station attr_reader :id, :address, :latitude, :longitude def initialize(marker) @id = marker.number @address = marker.address @latitude = marker.lat @longitude = marker.lng end def distance_to(m_lat, m_lng) d_lat = (@latitude - m_lat).to_rad d_lng = (@longitude - m_lng).to_rad a = Math.sin(d_lat / 2) * Math.sin(d_lat / 2) + Math.cos(m_lat.to_rad) * Math.cos(@latitude.to_rad) * Math.sin(d_lng / 2) * Math.sin(d_lng / 2) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) 6371 * c end end end class Numeric def to_rad self * Math::PI / 180 end end
RSpec.shared_context "yammer POST" do |endpoint| let(:request_url) { "https://www.yammer.com/api/v1/#{endpoint}" } let!(:mock) { stub_request(:post, request_url).with( headers: { 'Authorization' => 'Bearer shakenn0tst1rr3d' } ). to_return( status: 201, body: {status: "ok"}.to_json, headers: { "Content-type": "application/json" } ) } end
# frozen_string_literal: true class InvitationMailer < ApplicationMailer def created(invitation) @invitation = invitation @company = invitation.company mail(to: @invitation.email, subject: "Join #{@company.name} on Lunchiatto") end end
require 'rails_helper' RSpec.describe ArtsType, type: :model do before { @model = FactoryGirl.build(:arts_type) } subject { @model } it { should respond_to(:name) } it { should respond_to(:description) } it { should be_valid } it { should have_and_belong_to_many(:media_items) } it { should validate_uniqueness_of(:name) } it { should validate_presence_of(:name) } end
class NewPostForm include Capybara::DSL def visit_page visit '/posts' click_on('New One') self end def fill_in_with(params = {}) fill_in('Title', with: params.fetch(:title, 'Make a Post')) fill_in('Body', with: 'Post content') self end def submit click_on('Create Post') self end end
class AddUniqueIndexToTaggings < ActiveRecord::Migration[5.0] def change add_index :taggings, [:note_id, :tag_id], unique: true end end
module Admin class RolesController < ApplicationController before_action :set_admin_role, only: [:show, :edit, :update, :destroy] # POST /admin/users/1/roles/1/assign # POST /admin/users/1/roles/1/assign.json def assign respond_to do |format| status = :ok begin user = Admin::User.find(params[:user_id]) if user.roles.exists?(params[:role_id]) flash[:alert] = 'The user has the role.' status = :not_modified destination_url = user else role = Admin::Role.find(params[:role_id]) end rescue ActiveRecord::RecordNotFound => e status = :not_found if user flash[:error] = 'Role not found' destination_url = user else flash[:error] = 'User not found' destination_url = admin_users_url end end if status == :ok destination_url = user begin user.roles << role flash[:notice] = 'The role was successfully assigned to the user.' rescue => e flash[:error] = 'Role assigning failed: ' + e.message status = :unprocessable_entity end end format.html { redirect_to destination_url } format.json { render json: params.merge(flash: flash), status: status, location: user } end end # POST /admin/users/1/roles/1/revoke # POST /admin/users/1/roles/1/revoke.json def revoke respond_to do |format| status = :ok begin user = Admin::User.find(params[:user_id]) user.roles.delete(params[:role_id]) rescue ActiveRecord::RecordNotFound => e if user flash[:alert] = 'The user didn\'t have the role' destination_url = user else flash[:error] = 'User not found' destination_url = admin_roles_url end status = :not_found end if status == :ok flash[:notice] = 'The role has removed' destination_url = user end format.html { redirect_to destination_url } format.json { render json: params.merge(flash: flash), status: status, location: user } end end # GET /admin/roles # GET /admin/roles.json def index @admin_roles = Admin::Role.all end # GET /admin/roles/1 # GET /admin/roles/1.json def show @obtained_res = @admin_role.resources.all.order(:res_seq) @target_res = Admin::Resource .joins("LEFT JOIN roles_resources " + "ON roles_resources.resource_id = admin_resources.id " + "AND roles_resources.role_id = #{params[:id]}") .where("roles_resources.resource_id is null") .order(:res_seq) end # GET /admin/roles/new def new @admin_role = Admin::Role.new @admin_role[:status] = 'A' end # GET /admin/roles/1/edit def edit end # POST /admin/roles # POST /admin/roles.json def create @admin_role = Admin::Role.new(admin_role_params) respond_to do |format| if @admin_role.save format.html { redirect_to @admin_role, notice: 'Role was successfully created.' } format.json { render :show, status: :created, location: @admin_role } else format.html { render :new } format.json { render json: @admin_role.errors, status: :unprocessable_entity } end end end # PATCH/PUT /admin/roles/1 # PATCH/PUT /admin/roles/1.json def update respond_to do |format| if @admin_role.update(admin_role_params) format.html { redirect_to @admin_role, notice: 'Role was successfully updated.' } format.json { render :show, status: :ok, location: @admin_role } else format.html { render :edit } format.json { render json: @admin_role.errors, status: :unprocessable_entity } end end end # DELETE /admin/roles/1 # DELETE /admin/roles/1.json def destroy @admin_role.destroy respond_to do |format| format.html { redirect_to admin_roles_url, notice: 'Role was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_admin_role @admin_role = Admin::Role.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def admin_role_params params.require(:admin_role).permit(:role_name, :role_desc, :status) end end end
ActiveRecord::Base.class_eval do def self.validate_mac_address( attr_names, options={} ) validates_format_of( attr_names, { :with => /^ [0-9A-F]{2} (?: [0-9A-F]{2} ){5} $/x, :allow_blank => false, :allow_nil => false, }.merge!( options ) ) end def self.validate_ip_address( attr_names, options={} ) validates_format_of( attr_names, { :with => /^ (?:25[0-5]|(?:2[0-4]|1\d|[1-9])?\d) (?:\.(?:25[0-5]|(?:2[0-4]|1\d|[1-9])?\d)){3} $/x, # OPTIMIZE IPv6 :allow_blank => false, :allow_nil => false, }.merge!( options ) ) end def self.validate_ip_port( attr_names, options={} ) validates_numericality_of( attr_names, { :only_integer => true, :greater_than => 0, :less_than => 65536, :allow_nil => false, }.merge!( options ) ) end def self.validate_netmask( attr_names, options={} ) configuration = { :allow_nil => false, :allow_blank => false, :with => /^( ((128|192|224|240|248|252|254)\.0\.0\.0) |(255\.(0|128|192|224|240|248|252|254)\.0\.0) |(255\.255\.(0|128|192|224|240|248|252|254)\.0) |(255\.255\.255\.(0|128|192|224|240|248|252|254)) )$/x } configuration.merge!( options ) validates_format_of( attr_names, configuration ) end def self.validate_hostname_or_ip( attr_names, options={} ) # Validate the server. This is the "host" rule from RFC 3261 # (but the patterns for IPv4 and IPv6 addresses have been fixed here). configuration = { :allow_nil => false, :allow_blank => false, :with => /^ (?: (?: (?: (?: [A-Za-z0-9] | [A-Za-z0-9] [A-Za-z0-9\-]* [A-Za-z0-9] ) \. )* (?: [A-Za-z] | [A-Za-z] [A-Za-z0-9\-]* [A-Za-z0-9] ) \.? ) | (?: (?: 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) (?: \. (?: 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ){3} ) | ( ( ( [0-9A-Fa-f]{1,4} [:] ){7} ( [0-9A-Fa-f]{1,4} | [:] ) )| ( ( [0-9A-Fa-f]{1,4} [:] ){6} ( [:] [0-9A-Fa-f]{1,4} | ( ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ( \. ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ){3} ) | [:] ) )| ( ( [0-9A-Fa-f]{1,4} [:] ){5} ( ( ( [:] [0-9A-Fa-f]{1,4} ){1,2} )| [:]( ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ( \. ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ){3} )| [:] ) )| ( ( [0-9A-Fa-f]{1,4} [:] ){4} ( ( ( [:] [0-9A-Fa-f]{1,4} ){1,3} ) | ( ( [:] [0-9A-Fa-f]{1,4} )? [:] ( ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ( \. ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ){3} ) ) | [:] ) )| ( ( [0-9A-Fa-f]{1,4} [:] ){3} ( ( ( [:] [0-9A-Fa-f]{1,4} ){1,4} ) | ( ( [:] [0-9A-Fa-f]{1,4} ){0,2} [:] ( ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ( \. ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ){3} ) ) | [:] ) )| ( ( [0-9A-Fa-f]{1,4} [:] ){2} ( ( ( [:] [0-9A-Fa-f]{1,4} ){1,5} ) | ( ( [:] [0-9A-Fa-f]{1,4} ){0,3} [:] ( ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ( \. ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ){3} ) ) | [:] ) )| ( ( [0-9A-Fa-f]{1,4} [:] ){1} ( ( ( [:] [0-9A-Fa-f]{1,4} ){1,6} ) | ( ( [:] [0-9A-Fa-f]{1,4} ){0,4} [:] ( ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ( \. ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ){3} ) ) | [:] ) )| ( [:] ( ( ( [:] [0-9A-Fa-f]{1,4} ){1,7} ) | ( ( [:] [0-9A-Fa-f]{1,4} ){0,5} [:] ( ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ( \. ( 25[0-5] | 2[0-4]\d | 1\d\d | [1-9]?\d ) ){3} ) ) | [:] ) ) ) ) $/x } configuration.merge!( options ) validates_format_of( attr_names, configuration ) end # Validate SIP username. This is the "user" rule from RFC 3261. def self.validate_username( attr_names, options={} ) configuration = { :allow_nil => false, :allow_blank => false, :with => /^ (?: (?: [A-Za-z0-9] | [\-_.!~*'()] ) | %[0-9A-F]{2} | [&=+$,;?\/] ){1,255} $/x } configuration.merge!( options ) validates_format_of( attr_names, configuration ) end # Validate SIP password. def self.validate_sip_password( attr_names, options={} ) configuration = { :allow_nil => true, :allow_blank => true, :with => /^ (?: (?: [A-Za-z0-9] | [\-_.!~*'()] ) | %[0-9A-F]{2} | [&=+$,] ){0,255} $/x } configuration.merge!( options ) validates_format_of( attr_names, configuration ) end end module CustomValidators # Validates a URL. # TODO Convert this into a proper ActiveRecord validator. # def self.validate_url( url_str ) return false if url_str.blank? require 'uri' begin uri = URI.parse( url_str ) return false if ! uri.absolute? return false if ! uri.hierarchical? return false if !( uri.is_a?( URI::HTTP ) || uri.is_a?( URI::HTTPS ) ) rescue URI::InvalidURIError return false end return true end end
class EditsToPlaceTable < ActiveRecord::Migration def up change_column :places, :name, :string, null:false end def down end end
require File.dirname(__FILE__) + '/../spec_helper' describe Category do it "should be valid" do Factory.build(:category).should be_valid end it "should require a name" do Factory.build(:category, :name => '').should_not be_valid end it "should assign tickets" do tickets = [Factory(:ticket)] Factory.build(:category, :tickets => tickets).tickets.should == tickets end end
require 'rails_helper' RSpec.describe User, type: :model do context "validations" do it { should embed_many(:sessions) } it { is_expected.to have_fields(:name).of_type(String) } it { is_expected.to have_fields(:lastname).of_type(String) } it { is_expected.to have_fields(:login).of_type(String) } it { is_expected.to have_fields(:password_digest).of_type(String) } it { is_expected.to have_fields(:sex).of_type(Mongoid::Boolean) } it { is_expected.to have_fields(:email).of_type(String) } it { is_expected.to have_fields(:phone).of_type(String) } it { is_expected.to have_fields(:avatar).of_type(String) } it { is_expected.to have_fields(:info).of_type(String) } it { is_expected.to have_fields(:telegram).of_type(String) } it { is_expected.to have_fields(:bithday).of_type(DateTime) } it { is_expected.to have_fields(:job_apply_date).of_type(DateTime) } it { is_expected.to have_fields(:date_dismissal).of_type(DateTime) } it { is_expected.to have_fields(:updated_at) } it { is_expected.to have_fields(:created_at) } it { is_expected.to validate_uniqueness_of(:login) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_presence_of(:lastname) } it { is_expected.to validate_presence_of(:login) } it { is_expected.to validate_presence_of(:sex) } it { is_expected.to validate_presence_of(:email) } it { is_expected.to validate_presence_of(:phone) } it { is_expected.to validate_presence_of(:bithday) } it { is_expected.to validate_presence_of(:password_digest) } it { is_expected.to validate_length_of(:name).with_maximum(30) } #within(1..31) } it { is_expected.to validate_length_of(:lastname).with_maximum(30) } it { is_expected.to validate_length_of(:info).with_maximum(300) } #it { is_expected.to validate_length_of(:password).with_minimum(6) } #it { should ensure_length_of(:name).is_at_most(30) } end #before { @user = FactoryGirl.create :user } #subject { @user } # attributes = [ # :name, # :lastname, # :login, # :password_digest, # :sex, # :email, # :phone, # :avatar, # :info, # :telegram, # :bithday, # :job_apply_date, # :date_dismissal, # :password, # :password_confirmation] # # attributes.each { |attribute| it { should respond_to attribute} } # # it { should be_valid } # # describe 'when name' do # describe 'is not presence' do # before { @user.name = " " } # # it { should_not be_valid } # end # # describe 'is long' do # before { @user.name = "a"*31 } # # it { should_not be_valid } # end # # describe 'is' do # before { @user.name = "a"*30 } # # it { should be_valid } # end # end # describe 'when email' do # describe 'is not presence' do # before { @user.email = " " } # # it { should_not be_valid } # end # # describe 'is not presence' do # before { @user.email = " " } # # it { should_not be_valid } # end # # describe 'is long' do # before { @user.email = "a"*51 } # # it { should_not be_valid } # end # # describe "format is invalid" do # it "should be invalid" do # addresses = %w[user@foo,com user_at_foo.org example.user@foo. # foo@bar_baz.com foo@bar+baz.com] # addresses.each do |invalid_address| # @user.email = invalid_address # expect(@user).to be_invalid # end # end # end # # describe "format is valid" do # it "should be valid" do # addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn] # addresses.each do |valid_address| # @user.email = valid_address # expect(@user).to be_valid # end # end # end # # describe 'is already taken' do # let(:dup_user) { @user.dup } # # specify { expect(dup_user).to be_invalid } # end # end # # describe 'when password' do # describe 'is not presence' do # #let(:user) {User.new(name: "Example User", email: "user@example.com", # # password: "foobar", password_confirmation: "foobar") } # before do # @user.password = " " # @user.password_confirmation = " " # end # # it { should_not be_valid } # end # # describe "doesn't match conformition" do # # let(:user) {User.new(name: "Example User", email: "user@example.com", # # password: "foobar", password_confirmation: "foobar") } # before do # @user.password = 'one' # @user.password_confirmation = 'not' # end # # it { should_not be_valid } # end # end # # describe 'when has post' do # let(:post) { FactoryGirl.create :post } # describe '(post nil class)' do # it { expect(@user.has_post?(nil)).to eq(false) } # end # # describe '(post new class)' do # before { post.user_id = nil } # # it { expect(@user.has_post?(post)).to eq(false) } # end # # describe '(post to another user)' do # before { post.user_id = @user.id + 2 } # # it { expect(@user.has_post?(post)).to eq(false) } # end # # describe '(post to current user)' do # before { post.user_id = @user.id } # # it { expect(@user.has_post?(post)).to eq(true) } # end # end end
class BooksController < ApplicationController skip_before_action :verify_authenticity_token before_action :set_book, only: %i[ show edit update destroy ] before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy] def index @books = Book.all end def show @book = Book.find(params[:id]) if user_signed_in? session = Stripe::Checkout::Session.create( payment_method_types: ['card'], customer_email: current_user.email, line_items: [{ name: @book.title, amount: (@book.price * 100), currency: 'aud', quantity: 1 }], payment_intent_data: { metadata: { user_id: current_user.id, book_id: @book.id } }, success_url: "#{root_url}payments/success?bookId=#{@book.id}", cancel_url: "#{root_url}books" ) @session_id = session.id end end def new @book = Book.new @book.build_author @book.build_publisher load_categories end def edit load_categories end def create @book = Book.new(book_params) @book.user = current_user if @book.save flash[:success] = "A new book was successfully created." redirect_to book_path(@book.id) else flash.now[:error] = @book.errors.full_messages.to_sentence render "new" end end def update if @book.update(book_params) flash[:success] = "Book updated." redirect_to book_path(@book.id) else render "edit" end end def destroy @book.destroy redirect_to books_path end def search if params[:q].blank? redirect_to request.referrer else @title = params[:q].downcase @books = Book.where("lower(title) LIKE ?", "%#{@title}%") end end private def set_book @book = Book.find(params[:id]) end def load_categories @categories = Category.all end def book_params params.require(:book).permit(:picture, :title, :edition, :pages, :date, :format, :price, :author_id, :publisher_id, :category_id, author_attributes: [:name], publisher_attributes: [:name]) end end
require 'test_helper' class CountryJpsControllerTest < ActionController::TestCase setup do @country_jp = country_jps(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:country_jps) end test "should get new" do get :new assert_response :success end test "should create country_jp" do assert_difference('CountryJp.count') do post :create, country_jp: { name: @country_jp.name } end assert_redirected_to country_jp_path(assigns(:country_jp)) end test "should show country_jp" do get :show, id: @country_jp assert_response :success end test "should get edit" do get :edit, id: @country_jp assert_response :success end test "should update country_jp" do put :update, id: @country_jp, country_jp: { name: @country_jp.name } assert_redirected_to country_jp_path(assigns(:country_jp)) end test "should destroy country_jp" do assert_difference('CountryJp.count', -1) do delete :destroy, id: @country_jp end assert_redirected_to country_jps_path end end
class TeamsController < ApplicationController def index @teams = Team.open_membership end def new @team = Team.new end def create @team = Team.new(team_params) if @team.save @team.users << current_user redirect_to team_path(@team) else render :new end end def show @team = Team.find(params[:id]) if @team.users.include?(current_user) @stories = @team.stories else @stories = @team.public_stories end @membership = Membership.new end private def team_params params.require(:team).permit(:name, :open_membership) end end
$:.push File.expand_path('../lib', __FILE__) require 'js_tools/version' Gem::Specification.new do |s| s.name = 'js_tools' s.version = JsTools::VERSION s.authors = ['Khrebtov Roman'] s.email = ['roman@alltmb.ru'] s.homepage = 'https://github.com/Hrom512/js_tools' s.summary = 'JS tools for rails' s.description = s.summary s.license = 'MIT' s.files = Dir['{app,lib}/**/*', 'Gemfile', 'MIT-LICENSE', 'README.md'] s.add_dependency 'rails', '>= 4.0' s.add_dependency 'coffee-rails' s.add_dependency 'sass-rails' end
require 'forwardable' module Extras # A class that provides a queue-like (first-in, first-out) # structure to clients class Fifo extend Forwardable def_delegators :@store, :length def initialize @store = Array.new end # Puts an object into the queue # # @param [Object] obj # @return [Fifo] The queue itself. def put!(obj) @store.push(obj) self end # Takes the least recently added element. # # @return [Object] whatever was stored in this queue. def take! @store.shift end end end
class ReceivableCheckSheet < ActiveRecord::Base belongs_to :user def self.to_download headers = %w(回収日 売掛金残高 Amazon残高 楽天残高 ヤフーショッピング残高 その他残高) csv_data = CSV.generate(headers: headers, write_headers: true, force_quotes: true) do |csv| all.find_each do |row| csv_column_values = [ row.receipt_date, row.balance_amount, row.amazon_amount, row.rakuten_amount, row.yahoo_shopping_amount, row.yafuoku_amount ] csv << csv_column_values end end csv_data.encode(Encoding::SJIS, :invalid => :replace, :undef => :replace, :replace => "?") end def self.admin_download headers = %w(ID user_id 回収日 売掛金残高 Amazon残高 楽天残高 ヤフーショッピング残高 その他残高) csv_data = CSV.generate(headers: headers, write_headers: true, force_quotes: true) do |csv| all.find_each do |row| csv_column_values = [ row.id, row.user_id, row.receipt_date, row.balance_amount, row.amazon_amount, row.rakuten_amount, row.yahoo_shopping_amount, row.yafuoku_amount ] csv << csv_column_values end end csv_data.encode(Encoding::SJIS, :invalid => :replace, :undef => :replace, :replace => "?") end end
# EventHub module module EventHub # Listner Class class ActorListener include Celluloid include Helper finalizer :cleanup def initialize(processor_instance) @actor_publisher = ActorPublisher.new_link @actor_watchdog = ActorWatchdog.new_link @connections = {} @processor_instance = processor_instance start end def start EventHub.logger.info("Listener is starting...") EventHub::Configuration.processor[:listener_queues].each_with_index do |queue_name, index| async.listen(queue_name: queue_name, index: index) end end def restart raise "Listener is restarting..." end def listen(args = {}) with_listen(args) do |connection, channel, consumer, queue, queue_name| EventHub.logger.info("Listening to queue [#{queue_name}]") consumer.on_delivery do |delivery_info, metadata, payload| EventHub.logger.info("#{queue_name}: [#{delivery_info.delivery_tag}]" \ " delivery") @processor_instance.statistics.measure(payload.size) do handle_payload(payload: payload, connection: connection, queue_name: queue_name, content_type: metadata[:content_type], priority: metadata[:priority], delivery_tag: delivery_info.delivery_tag) channel.acknowledge(delivery_info.delivery_tag, false) end EventHub.logger.info("#{queue_name}: [#{delivery_info.delivery_tag}]" \ " acknowledged") end queue.subscribe_with(consumer, block: false) end rescue => error EventHub.logger.error("Unexpected exception: #{error}. It should restart now with this exception...") raise end def with_listen(args = {}, &block) connection = create_bunny_connection connection.start queue_name = args[:queue_name] @connections[queue_name] = connection channel = connection.create_channel channel.prefetch(1) queue = channel.queue(queue_name, durable: true) consumer = EventHub::Consumer.new(channel, queue, EventHub::Configuration.name + "-" + args[:index].to_s, false) yield connection, channel, consumer, queue, queue_name end def handle_payload(args = {}) response_messages = [] connection = args[:connection] # convert to EventHub message message = EventHub::Message.from_json(args[:payload]) # append to execution history message.append_to_execution_history(EventHub::Configuration.name) # return invalid messages to dispatcher if message.invalid? response_messages << message EventHub.logger.info("-> #{message} => return invalid to dispatcher") else begin response_messages = @processor_instance.send(:handle_message, message, pass_arguments(args)) rescue => exception # this catches unexpected exceptions in handle message method # deadletter the message via dispatcher message.status_code = EventHub::STATUS_DEADLETTER message.status_message = exception.to_s EventHub.logger.info("-> #{message} => return exception to dispatcher") response_messages << message end end Array(response_messages).each do |message| publish(message: message.to_json, connection: connection) end end def pass_arguments(args = {}) keys_to_pass = [:queue_name, :content_type, :priority, :delivery_tag] args.select { |key| keys_to_pass.include?(key) } end def cleanup EventHub.logger.info("Listener is cleaning up...") # close all open connections return unless @connections @connections.values.each do |connection| connection&.close end end def publish(args) @actor_publisher.publish(args) end end end
class Payroll < ActiveRecord::Base has_many :payroll_details belongs_to :worker accepts_nested_attributes_for :payroll_details, :allow_destroy => true def self.getWorker(word, name) mysql_result = ActiveRecord::Base.connection.execute(" SELECT e.id, e.name, e.second_name, e.paternal_surname, e.maternal_surname FROM workers w, entities e WHERE ( e.name LIKE '%#{word}%' OR e.second_name LIKE '%#{word}%' OR e.paternal_surname LIKE '%#{word}%' OR e.maternal_surname LIKE '%#{word}%' ) AND e.maternal_surname IS NOT NULL AND e.id = w.entity_id ") return mysql_result end def self.show_w(cost_center_id, display_length, pager_number, keyword = '') result = Array.new if keyword != '' && pager_number != 'NaN' part_people = ActiveRecord::Base.connection.execute(" SELECT wo.id, ent.name, ent.paternal_surname, ent.maternal_surname FROM workers wo, entities ent, articles art, worker_contracts wc WHERE wo.entity_id = ent.id AND wc.worker_id = wo.id AND wc.article_id = art.id AND wo.cost_center_id = " + cost_center_id.to_s + " AND (wo.id LIKE '%" + keyword + "%' OR ent.name LIKE '%" + keyword + "%' OR ent.paternal_surname LIKE '%" + keyword + "%' OR ent.maternal_surname LIKE '%" + keyword + "%' OR pow.name LIKE '%" + keyword + "%' OR art.name LIKE '%" + keyword + "%' OR wo.email LIKE '%" + keyword + "%' OR ent.date_of_birth LIKE '%" + keyword + "%' OR ent.address LIKE '%" + keyword + "%') Group by wo.id ORDER BY wo.id ASC LIMIT " + display_length + " OFFSET " + pager_number ) elsif pager_number != 'NaN' part_people = ActiveRecord::Base.connection.execute(" SELECT wo.id, ent.name, ent.paternal_surname, ent.maternal_surname FROM workers wo, entities ent, articles art, worker_contracts wc WHERE wo.entity_id = ent.id AND wc.worker_id = wo.id AND wc.article_id = art.id AND wo.cost_center_id = " + cost_center_id.to_s + " Group by wo.id ORDER BY wo.id ASC LIMIT " + display_length + " OFFSET " + pager_number ) else part_people = ActiveRecord::Base.connection.execute(" SELECT wo.id, ent.name, ent.paternal_surname, ent.maternal_surname FROM workers wo, entities ent, articles art, worker_contracts wc WHERE wo.entity_id = ent.id AND wc.worker_id = wo.id AND wc.article_id = art.id AND wo.cost_center_id = " + cost_center_id.to_s + " Group by wo.id ORDER BY wo.id ASC LIMIT " + display_length ) end part_people.each do |part_person| result << [ part_person[0], part_person[1], part_person[2], part_person[3], "<a class='btn btn-success btn-xs' onclick=javascript:load_url_ajax('/payrolls/payrolls/"+part_person[0].to_s+"','content',null,null,'GET')>Ver Datos de Pago</a>" + "<a class='btn btn-info btn-xs' onclick=javascript:load_url_ajax('/payrolls/payrolls/new','content',{worker_id:'" + part_person[0].to_s + "'},null,'GET')>Datos de Pago</a>"+ "<a class='btn btn-warning btn-xs' onclick=javascript:load_url_ajax('/payrolls/payrolls/" + part_person[0].to_s + "/edit','content',null,null,'GET')>Editar Datos de Pago</a>" ] end return result end end
require 'rake' require 'rake/file_utils_ext' class SnapDeploy::Provider::Heroku < Clamp::Command SnapDeploy::CLI.subcommand 'heroku', 'deploy to heroku', self include SnapDeploy::CLI::DefaultOptions include SnapDeploy::Helpers include Rake::FileUtilsExt option '--app-name', 'APP_NAME', 'The name of the heroku app to deploy', :required => true option '--region', 'REGION', 'The name of the region', :default => 'us' option '--config-var', 'KEY=VALUE', 'The name of the config variables', :multivalued => true option '--buildpack-url', 'BUILDPACK_URL', 'The url of the heroku buildpack' do |url| require 'uri' if url =~ URI::regexp(%w(http https git)) url else raise 'The buildpack url does not appear to be a url.' end end option '--stack-name', 'STACK_NAME', 'The name of the heroku stack', :default => 'cedar' option '--[no-]db-migrate', :flag, 'If the db should be automatically migrated', :default => false def initialize(*args) super require 'snap_deploy/provider/heroku/api' require 'netrc' require 'ansi' require 'rendezvous' require 'tempfile' end def execute check_auth maybe_create_app setup_configuration git_push maybe_db_migrate end private SLEEP_INTERVAL = 0.1 def maybe_db_migrate return unless db_migrate? log ANSI::Code.ansi("Attempting to run `#{migrate_command}`", :cyan) dyno = client.dyno.create(app_name, :command => %Q{#{migrate_command}; echo "Command exited with $?"}, :attach => true) reader, writer = IO.pipe thread = Thread.new do Rendezvous.start(:input => StringIO.new, :output => writer, :url => dyno['attach_url']) end begin exit_code = Timeout.timeout(300) do copy_to_stdout(thread, reader, writer) end unless exit_code error ANSI::Code.ansi('The remote command execution may have failed to return an exit code.', :red) exit(-1) end if exit_code != 0 error ANSI::Code.ansi("The remote command exited with status #{exit_code}", :red) exit(exit_code) end rescue Timeout::Error raise Timeout::Error('There was no output generated in 300 seconds.') end thread.join(SLEEP_INTERVAL) end def copy_to_stdout(thread, reader, writer) writer.sync = true exit_code = nil tempfile = Tempfile.new('heroku-console-log') loop do nothing_to_read = if IO.select([reader], nil, nil, SLEEP_INTERVAL) contents = (reader.readpartial(4096) rescue nil) unless writer.closed? copy_output(contents, tempfile) !!contents else true end thread_dead = if thread.join(SLEEP_INTERVAL) writer.close unless writer.closed? true end break if thread_dead && nothing_to_read end # read everything one last time copy_output(reader.read, tempfile) # go back a bit in the console output to check on the exit status, aka poor man's tail(1) tempfile.seek([-tempfile.size, -32].max, IO::SEEK_END) if last_line = tempfile.readlines.last if match_data = last_line.match(/Command exited with (\d+)/) exit_code = match_data[1].to_i end end exit_code end def copy_output(contents, tempfile) return unless contents tempfile.print contents print contents end def migrate_command 'rake db:migrate --trace' end def maybe_create_app print ANSI::Code.ansi('Checking to see if app already exists... ', :cyan) if app_exists? print ANSI::Code.ansi("OK\n", :green) else print ANSI::Code.ansi("No\n", :yellow) create_app end end def setup_configuration print ANSI::Code.ansi('Setting up config vars... ', :cyan) # config_var_list returns a dup configs = config_var_list configs << "BUILDPACK_URL=#{buildpack_url}" if buildpack_url if configs.empty? print ANSI::Code.ansi("No config vars specified\n", :green) return end existing_vars = client.config_var.info(app_name) vars = configs.inject({}) do |memo, var| key, value = var.split('=', 2) if existing_vars[key] != value memo[key] = value end memo end if vars.empty? print ANSI::Code.ansi("No change required\n", :green) else print ANSI::Code.ansi("\nUpdating config vars #{vars.keys.join(', ')}... ", :cyan) client.config_var.update(app_name, vars) print ANSI::Code.ansi("OK\n", :green) end end def git_push if pull_request_number print ANSI::Code.ansi("Pushing upstream branch #{snap_upstream_branch} from pull request #{pull_request_number} to heroku.\n", :cyan) else print ANSI::Code.ansi("Pushing branch #{snap_branch} to heroku.\n", :cyan) end cmd = "git push https://git.heroku.com/#{app_name}.git HEAD:refs/heads/master -f" puts "$ #{ANSI::Code.ansi(cmd, :green)}" sh(cmd) do |ok, res| raise "Could not push to heroku remote. The exit code was #{res.exitstatus}." unless ok end end def create_app print ANSI::Code.ansi('Creating app on heroku since it does not exist... ', :cyan) client.app.create({ name: app_name, region: region, stack: stack_name }) print ANSI::Code.ansi("Done\n", :green) end def app_exists? !!client.app.info(app_name) rescue Excon::Errors::Unauthorized, Excon::Errors::Forbidden => e raise "You are not authorized to check if the app exists, perhaps you don't own that app?. The server returned status code #{e.response[:status]}." rescue Excon::Errors::NotFound => ignore false end def check_auth print ANSI::Code.ansi('Checking heroku credentials... ', :cyan) client.account.info print ANSI::Code.ansi("OK\n", :green) rescue Excon::Errors::HTTPStatusError => e raise "Could not connect to heroku to check your credentials. The server returned status code #{e.response[:status]}." end def client SnapDeploy::Provider::Heroku::API.connect_oauth(token) end def netrc @netrc ||= Netrc.read end def token @token ||= netrc['api.heroku.com'].password end def default_options { } end end
describe SamlIdpController do render_views describe '/api/saml/logout' do it 'calls UserOtpSender#reset_otp_state' do user = create(:user, :signed_up) sign_in user otp_sender = instance_double(UserOtpSender) allow(UserOtpSender).to receive(:new).with(user).and_return(otp_sender) expect(otp_sender).to receive(:reset_otp_state) delete :logout end end end