text
stringlengths
10
2.61M
class CreateAreas < ActiveRecord::Migration[5.0] def change create_table :areas do |t| t.string :nombre t.integer :state_id t.string :poblacion t.string :edad t.string :hogares t.string :con_hijos t.string :sin_hijos t.string :rpc t.string :viviendas t.string :porcentaje t.string :propia t.string :hipoteca t.string :alquilada t.string :otros t.string :activa t.string :paro t.string :tasa_paro t.string :pib t.string :gasto t.string :precio t.string :dentistas t.timestamps end end end
#!/usr/bin/ruby -w # # Test etch's handling of various actions: pre, post, setup, test, etc. # require File.expand_path('etchtest', File.dirname(__FILE__)) class EtchActionTests < Test::Unit::TestCase include EtchTests def setup # Generate a file to use as our etch target/destination @targetfile = released_tempfile #puts "Using #{@targetfile} as target file" # Generate a directory for our test repository @repodir = initialize_repository @server = get_server(@repodir) # Create a directory to use as a working directory for the client @testroot = tempdir #puts "Using #{@testroot} as client working directory" # Generate another file to use as our link target @destfile = released_tempfile #puts "Using #{@destfile} as link destination file" end def test_actions # # Basic tests to ensure that actions are performed under normal # circumstances # testname = 'basic action test' FileUtils.mkdir_p("#{@repodir}/source/#{@targetfile}") File.open("#{@repodir}/source/#{@targetfile}/config.xml", 'w') do |file| file.puts <<-EOF <config> <server_setup> <exec>echo server_setup >> #{@repodir}/server_setup</exec> </server_setup> <setup> <exec>echo setup >> #{@repodir}/setup</exec> </setup> <pre> <exec>echo pre >> #{@repodir}/pre</exec> </pre> <file> <warning_file/> <source> <plain>source</plain> </source> </file> <test_before_post> <exec>echo test_before_post >> #{@repodir}/test_before_post</exec> </test_before_post> <post> <exec_once>echo exec_once >> #{@repodir}/exec_once</exec_once> <exec_once_per_run>echo exec_once_per_run >> #{@repodir}/exec_once_per_run</exec_once_per_run> <exec_once_per_run>echo exec_once_per_run >> #{@repodir}/exec_once_per_run</exec_once_per_run> <exec>echo post >> #{@repodir}/post</exec> </post> <test> <exec>echo test >> #{@repodir}/test</exec> </test> </config> EOF end sourcecontents = "This is a test\n" File.open("#{@repodir}/source/#{@targetfile}/source", 'w') do |file| file.write(sourcecontents) end assert_etch(@server, @testroot, :testname => testname) # Verify that the actions were executed # The setup actions will get run several times as we loop # back and forth with the server sending original sums and # contents. So just verify that they were run at least once. assert_match("server_setup\n", get_file_contents("#{@repodir}/server_setup"), 'server_setup') assert_match("setup\n", get_file_contents("#{@repodir}/setup"), 'setup') assert_equal("pre\n", get_file_contents("#{@repodir}/pre"), 'pre') assert_equal( "exec_once\n", get_file_contents("#{@repodir}/exec_once"), 'exec_once') assert_equal( "exec_once_per_run\n", get_file_contents("#{@repodir}/exec_once_per_run"), 'exec_once_per_run') assert_equal( "test_before_post\n", get_file_contents("#{@repodir}/test_before_post"), 'test_before_post') assert_equal("post\n", get_file_contents("#{@repodir}/post"), 'post') assert_equal("test\n", get_file_contents("#{@repodir}/test"), 'test') # Run etch again and make sure that the exec_once command wasn't run # again assert_etch(@server, @testroot, :testname => 'action test, exec_once') assert_equal("exec_once\n", get_file_contents("#{@repodir}/exec_once"), 'exec_once_2nd_check') end def test_failed_setup # # Test a failed setup command to ensure etch aborts # testname = 'failed setup' # Put some text into the original file so that we can make sure it # is not touched. origcontents = "This is the original text\n" File.delete(@targetfile) File.open(@targetfile, 'w') do |file| file.write(origcontents) end FileUtils.mkdir_p("#{@repodir}/source/#{@targetfile}") File.open("#{@repodir}/source/#{@targetfile}/config.xml", 'w') do |file| file.puts <<-EOF <config> <setup> <exec>false</exec> </setup> <file> <warning_file/> <source> <plain>source</plain> </source> </file> </config> EOF end sourcecontents = "This is a test\n" File.open("#{@repodir}/source/#{@targetfile}/source", 'w') do |file| file.write(sourcecontents) end assert_etch(@server, @testroot, :errors_expected => true, :testname => testname) # Verify that the file was not touched assert_equal(origcontents, get_file_contents(@targetfile), 'failed setup') end def test_failed_pre # # Test a failed pre command to ensure etch aborts # testname = 'failed pre' # Put some text into the original file so that we can make sure it # is not touched. origcontents = "This is the original text\n" File.delete(@targetfile) File.open(@targetfile, 'w') do |file| file.write(origcontents) end FileUtils.mkdir_p("#{@repodir}/source/#{@targetfile}") File.open("#{@repodir}/source/#{@targetfile}/config.xml", 'w') do |file| file.puts <<-EOF <config> <pre> <exec>false</exec> </pre> <file> <warning_file/> <source> <plain>source</plain> </source> </file> </config> EOF end sourcecontents = "This is a test\n" File.open("#{@repodir}/source/#{@targetfile}/source", 'w') do |file| file.write(sourcecontents) end assert_etch(@server, @testroot, :errors_expected => true, :testname => testname) # Verify that the file was not touched assert_equal(origcontents, get_file_contents(@targetfile), 'failed pre') end def test_failed_test # # Run a test where the test action fails, ensure that the original # target file is restored and any post actions re-run afterwards # testname = 'failed test' # Put some text into the original file so that we can make sure it # is restored. origcontents = "This is the original text\n" File.delete(@targetfile) File.open(@targetfile, 'w') do |file| file.write(origcontents) end FileUtils.mkdir_p("#{@repodir}/source/#{@targetfile}") File.open("#{@repodir}/source/#{@targetfile}/config.xml", 'w') do |file| file.puts <<-EOF <config> <file> <warning_file/> <overwrite_directory/> <source> <plain>source</plain> </source> </file> <post> <exec>echo post >> #{@repodir}/post</exec> </post> <test> <exec>false</exec> </test> </config> EOF end # Change the source file so that we can see whether the original was # restored or not File.open("#{@repodir}/source/#{@targetfile}/source", 'w') do |file| file.write("Testing a failed test\n") end assert_etch(@server, @testroot, :testname => testname) # Verify that the original was restored, and that post was run twice assert_equal(origcontents, get_file_contents(@targetfile), 'failed test target') assert_equal("post\npost\n", get_file_contents("#{@repodir}/post"), 'failed test post') end def test_failed_test_before_post # # Run a test where the test_before_post action fails, ensure that # post is not run # testname = 'failed test_before_post' FileUtils.mkdir_p("#{@repodir}/source/#{@targetfile}") File.open("#{@repodir}/source/#{@targetfile}/config.xml", 'w') do |file| file.puts <<-EOF <config> <file> <warning_file/> <overwrite_directory/> <source> <plain>source</plain> </source> </file> <test_before_post> <exec>false</exec> </test_before_post> <post> <exec>echo post >> #{@repodir}/post</exec> </post> </config> EOF end assert_etch(@server, @testroot, :errors_expected => true, :testname => testname) # Verify that post was not run assert(!File.exist?("#{@repodir}/post"), 'failed test_before_post post') # # Run a test where the test action fails, and the original target file # is a symlink. Ensure that the symlink is restored. # testname = 'failed test_before_post symlink' # Prepare the target File.delete(@targetfile) if File.exist?(@targetfile) File.symlink(@destfile, @targetfile) assert_etch(@server, @testroot, :errors_expected => true, :testname => testname) # Verify that the original symlink was restored assert_equal(@destfile, File.readlink(@targetfile), 'failed test symlink') # # Run a test where the test action fails, and the original target file # is a directory. Ensure that the directory is restored. # testname = 'failed test_before_post directory' # Prepare the target File.delete(@targetfile) if File.exist?(@targetfile) Dir.mkdir(@targetfile) File.open("#{@targetfile}/testfile", 'w') { |file| } assert_etch(@server, @testroot, :errors_expected => true, :testname => testname) # Verify that the original directory was restored assert(File.directory?(@targetfile), 'failed test directory') assert(File.file?("#{@targetfile}/testfile"), 'failed test directory contents') # # Run a test where the test action fails, and there is no original # target file. Ensure that the end result is that there is no file left # behind. # testname = 'failed test_before_post no original' # We can reuse the config.xml from the previous test # Clean up from previous runs if File.exist?(@targetfile) || File.symlink?(@targetfile) FileUtils.rm_rf(@targetfile) end File.delete("#{@repodir}/post") if File.exist?("#{@repodir}/post") assert_etch(@server, @testroot, :errors_expected => true, :testname => testname) # Verify that the lack of an original file was restored assert(!File.exist?(@targetfile) && !File.symlink?(@targetfile), 'failed test no original file') end def test_nested_target # # Run a test where a test action is defined and the target file is in a # directory that does not exist yet, thus requiring that we make the # directory before creating the backup (or rather the NOORIG marker in # this case). We had a bug where that failed, as the code to make the # directory structure was after the code to make the backup. # # I.e. configuration to create /etc/foo/bar, but /etc/foo does not exist. # The backup that is created when a test is defined (so that we can roll # back if the test fails) is made as /etc/foo/bar.XXXXX, which requires # that /etc/foo exist first. # testname = 'test action with nested target' nestedtargetdir = deleted_tempfile nestedtargetfile = File.join(nestedtargetdir, 'etchnestedtest') FileUtils.mkdir_p("#{@repodir}/source/#{nestedtargetfile}") File.open("#{@repodir}/source/#{nestedtargetfile}/config.xml", 'w') do |file| file.puts <<-EOF <config> <file> <warning_file/> <source> <plain>source</plain> </source> </file> <test> <exec>true</exec> </test> </config> EOF end sourcecontents = "Testing a nested target\n" File.open("#{@repodir}/source/#{nestedtargetfile}/source", 'w') do |file| file.write(sourcecontents) end assert_etch(@server, @testroot, :testname => testname) # Verify that the file was created properly assert_equal(sourcecontents, get_file_contents(nestedtargetfile), 'nested target with test') FileUtils.rm_rf(nestedtargetdir) end def test_action_with_xml_escape # # Test an action requiring XML escape # The XML spec says that < and & must be escaped almost anywhere # outside of their use as markup. That includes the character data of # actions. # http://www.w3.org/TR/2006/REC-xml-20060816/#syntax # So if the user wants to use something like && in an action they must # escape the & with &amp; # testname = 'XML escape' FileUtils.mkdir_p("#{@repodir}/source/#{@targetfile}") File.open("#{@repodir}/source/#{@targetfile}/config.xml", 'w') do |file| file.puts <<-EOF <config> <file> <warning_file/> <source> <plain>source</plain> </source> </file> <post> <exec>true &amp;&amp; echo post >> #{@repodir}/post_with_escape</exec> </post> </config> EOF end sourcecontents = "This is a test of a post with XML escapes\n" File.open("#{@repodir}/source/#{@targetfile}/source", 'w') do |file| file.write(sourcecontents) end assert_etch(@server, @testroot, :testname => testname) # Verify that the action was executed assert_equal("post\n", get_file_contents("#{@repodir}/post_with_escape"), 'post with escape') end def test_action_with_env # # Test an action involving passing an environment variable # testname = 'action with environment variable' FileUtils.mkdir_p("#{@repodir}/source/#{@targetfile}") File.open("#{@repodir}/source/#{@targetfile}/config.xml", 'w') do |file| file.puts <<-EOF <config> <file> <warning_file/> <source> <plain>source</plain> </source> </file> <post> <exec>TESTVAR=testvalue #{@repodir}/post_with_env</exec> </post> </config> EOF end sourcecontents = "This is a test of a post with an environment variable\n" File.open("#{@repodir}/source/#{@targetfile}/source", 'w') do |file| file.write(sourcecontents) end File.open("#{@repodir}/post_with_env", 'w') do |file| file.write <<EOF #!/bin/sh echo $TESTVAR >> #{@repodir}/post_with_env_output EOF end File.chmod(0755, "#{@repodir}/post_with_env") assert_etch(@server, @testroot, :testname => testname) # Verify that the action was executed assert_equal("testvalue\n", get_file_contents("#{@repodir}/post_with_env_output"), 'post with environment variable') end def teardown remove_repository(@repodir) FileUtils.rm_rf(@testroot) FileUtils.rm_rf(@targetfile) FileUtils.rm_f(@destfile) end end
# frozen_string_literal: true class Election < ApplicationRecord belongs_to :annual_meeting, -> { where type: 'AnnualMeeting' }, class_name: 'AnnualMeeting', inverse_of: :elections belongs_to :member belongs_to :role validates :member_id, :role_id, presence: true scope :current, ->(now = Time.current) { includes(:annual_meeting).references(:annual_meetings) .where(<<~SQL.squish, now: now) events.start_at <= :now AND (events.start_at + interval '1 year' * years + interval '1 month') >= :now AND NOT EXISTS ( SELECT 1 FROM elections e2 JOIN events am2 ON am2.id = e2.annual_meeting_id WHERE e2.role_id = elections.role_id AND am2.start_at > events.start_at AND am2.start_at <= :now ) SQL } scope :on_the_board, -> { includes(:role).where.not(roles: { years_on_the_board: nil }) } scope :not_on_the_board, -> { includes(:role).where(roles: { years_on_the_board: nil }) } def from annual_meeting.start_at.to_date end def to annual_meeting.next&.start_at&.to_date end def elected_name member.name end def elected_contact { name: member.name, email: member.email || member.emails.first } end end
module Madness # Handle command line execution. Used by bin/madness. class CommandLine include Singleton include Colsole # Launch the server def execute(argv=[]) launch_server_with_options argv end private # Execute the docopt engine to parse the options and then launch the # server. def launch_server_with_options(argv) doc = File.read File.expand_path('docopt.txt', __dir__) begin args = Docopt::docopt(doc, argv: argv, version: VERSION) set_config args build_index if config.index launch_server unless args['--and-quit'] rescue Docopt::Exit => e puts e.message end end # Launch the server, but not before doing some checks and making sure # we ask it to "prepare". This will set the server options such as port # and static files folder. def launch_server unless File.directory? config.path STDERR.puts "Invalid path (#{config.path})" return end show_status Server.prepare Server.run! end # Get the arguments as provided by docopt, and set them to our own # config object. def set_config(args) config.path = args['PATH'] if args['PATH'] config.port = args['--port'] if args['--port'] config.bind = args['--bind'] if args['--bind'] config.autoh1 = false if args['--no-auto-h1'] config.highlighter = false if args['--no-syntax'] config.line_numbers = false if args['--no-line-numbers'] config.index = true if args['--index'] config.development = true if args['--development'] end # Say hello to everybody when the server starts, showing the known # config. def show_status say_status :start, 'the madness' say_status :env, config.development ? 'development' : 'production', :txtblu say_status :listen, "#{config.bind}:#{config.port}", :txtblu say_status :path, File.realpath(config.path), :txtblu say_status :use, config.filename if config.file_exist? say "-" * 40 end def build_index say_status :start, 'indexing' Search.new.build_index say_status :done, 'indexing' end def config @config ||= Settings.instance end end end
require 'exchange_rate' RSpec.describe ExchangeRate do describe 'parsing the xml' do before(:each) do @yesterday = Date.today.prev_day @parser = XMLParser.new @exchange_rate = ExchangeRate.new(Date.new(2018, 8, 3), 'EUR', 'USD') end it 'should set the xml file' do @parser.get_rate(@exchange_rate) expect(@parser.file).to eq './lib/rates/daily_rates.xml' end it 'should get the date of the first item in the row' do expect(@parser.get_rate(@exchange_rate)).to eq 1.1588 end context 'invalid data' do it 'should throw an error if the date is not supported' do test_date = Date.today - 90 @exchange_rate = ExchangeRate.new(test_date, 'EUR', 'USD') expect {@parser.get_rate(@exchange_rate)}.to raise_error("Date must be within the past 90 days.") end it 'should throw an error if the base currency is not supported' do @exchange_rate = ExchangeRate.new(@yesterday, 'test', 'USD') expect {@parser.get_rate(@exchange_rate)}.to raise_error("The base currency test is not supported.") end it 'should throw an error if the counter currency is not supported' do @exchange_rate = ExchangeRate.new(@yesterday, 'EUR', 'test') expect {@parser.get_rate(@exchange_rate)}.to raise_error("The counter currency test is not supported.") end end end end
module DelayedCell class Proxy def initialize(target) @queue = Queue.new target end def method_missing(method, *args, &block) @queue.push Job.new(method, args) end end end
require 'logger' module GooglePlay module Log @loggers = {} def logger @logger ||= Log.logger_for(self.class.name) end def self.logger_for(klass) @loggers[klass] ||= configure_logger_for(klass) end def self.configure_logger_for(klass) logger = Logger.new(STDOUT) logger.progname = klass logger end end end
require "help.rb" module TestsHelp ##################################### # Private section # ##################################### @@TESTHELP=Hash.new() private class TestsHelp_Err < StandardError end class TestSection def initialize() @entries = Hash.new @description = "" end def description @description end def description=(des) @description = des end def entries @entries end end class TestEntry attr_reader :name, :version, :environement,:type, :help @parameters=[] def initialize(name, version, environement, type, prerequisites, parameters, coverage, results, example, author) @name=name @version=version @environement=environement @type=type @prerequisites=prerequisites @parameters=parameters @coverage=coverage @results=results @example=example @author=author end def makeHelp @help="" @help << "<table class='test'>" # First raw : [TestName | Version ] @help << "<tr bgcolor=#d0d0d0>" @help << "<td class='description'>Name</td>" @help << "<td class='center_content'><span class='test_name'>%s</span> ( %s )</td>" %[@name,@version] @help << "</tr>" # Second raw : [ Environement | Type ] @help << "<tr bgcolor=#f0f0f0>" @help << "<td class='description'>Environement | Type</td>" @help << "<td class='center_content'>%s | %s </td>" %[@environement,@type] @help << "</tr>" # Third raw : [ Prequisites ] @help << "<tr bgcolor=#d0d0d0>" @help << "<td class='description'>Prerequisites</td>" @help << "<td class='justify_content'>%s</td>" % @prerequisites @help << "</tr>" # Fourth raw : [ Parameters ] @help << "<tr bgcolor=#f0f0f0>" @help << "<td class='description'>Parameters</td>" @help << "<td class='justify_content'>" @help << "<ul>" @parameters.each do |parameterDescription| @help << "<li class='parameter_li'>" @help << "<span class='parameter_name'>%s</span> " % parameterDescription[0] @help << "<span class='parameter_default'> ( default : %s )</span> " % parameterDescription[1] @help << "</li>" @help << "<span class='parameter_description'> %s</span> " % parameterDescription[2] end @help << "</ul>" @help << "</td>" @help << "</tr>" # Fifth raw : [ Test coverage ] @help << "<tr bgcolor=#d0d0d0>" @help << "<td class='description'>Test coverage</td>" @help << "<td class='justify_content'>%s</td>" % @coverage @help << "</tr>" # Sixth raw : [ Results ] @help << "<tr bgcolor=#f0f0f0>" @help << "<td class='description'>Results</td>" @help << "<td class='justify_content'>%s</td>" % @results @help << "</tr>" # Seventh raw : [ Example ] @help << "<tr bgcolor=#d0d0d0>" @help << "<td class='description'>Example</td>" @help << "<td class='left_content'>%s</td>" % @example @help << "</tr>" # Eighth raw : [ Author ] @help << "<tr bgcolor=#f0f0f0>" @help << "<td class='description'>Author</td>" @help << "<td class='justify_content'>%s</td>" % @author @help << "</tr>" @help << "</table>" return @help end end def addTestSection(str_section) @@TESTHELP[str_section] = TestSection.new() end ##################################### # Public section # ##################################### public def TestsHelp.addTestHelpEntry(name, version, environement, type, prerequisites, parameters, coverage, results, example, author) if(!@@TESTHELP[environement]) then addTestSection(environement) end @@TESTHELP[environement].entries[name]=TestEntry.new( name, version, environement, type, prerequisites, parameters, coverage, results, example, author ) end def TestsHelp.saveToFiles(tests_list_file="//Atlas/n/users/cooltester/public_html/tests_list.php", tests_content_file="//Atlas/n/users/cooltester/public_html/tests_content.php") tests_list="" tests_content="" test_href=0 @@TESTHELP.sort.each do |section| sectionName=section[0] sectionObject=section[1] # Add testSection informations. tests_list << "<a href='##{sectionName}' class='test_section_link'>#{sectionName}</a> <br />" tests_content << "<br />" tests_content << "<span class='test_section_main'> <a name='#{sectionName}'> <h1> #{sectionName} :</h1> </a></span>" sectionObject.entries.sort.each do |test| testName=test[0] testEntry=test[1] tests_list << "<a href='##{test_href}' class='text_linkgray'>#{testName}</a> <br />" tests_content << "<span class='text_main'> <a name='#{test_href}'> <h2> #{testName} :</h2> </a></span>" tests_content << testEntry.makeHelp tests_content << "<br />" test_href+=1 end end begin File.open(tests_list_file,"wb") do |file| puts "html><font color='blue'>"+"Writting tests list in #{tests_list_file}..." + "</font>" file << tests_list end puts "Done successfully" File.open(tests_content_file,"wb") do |file| puts "html><font color='blue'>"+"Writting tests description in #{tests_content_file}..." + "</font>" file << tests_content end puts "Done successfully" rescue puts "html><font color='red'>"+ "Failed !" + "</font>" raise TestsHelp_Err , "Error while writting tests help" + "#{$!}" end end end
require_relative '02_searchable' require 'active_support/inflector' # bundle exec rspec spec/03_associatable_spec.rb # Phase IIIa class AssocOptions attr_accessor( :foreign_key, :class_name, :primary_key ) def model_class #go from a class name to a class object @class_name.constantize end def table_name #call object.table_name to get associated table model_class.table_name end end class BelongsToOptions < AssocOptions #self object belongs to name def initialize(name, options = {}) defaults = { :foreign_key => "#{name}_id".to_sym, :class_name => name.to_s.camelcase, :primary_key => :id } #creates default values #option to override default values with options hash defaults.keys.each do |key| self.send("#{key}=", options[key] || defaults[key]) end end end class HasManyOptions < AssocOptions #name obj belongs to self obj def initialize(name, self_class_name, options = {}) defaults = { :foreign_key => "#{self_class_name.underscore}_id".to_sym, :class_name => name.to_s.singularize.camelcase, :primary_key => :id } #override default values if you choose defaults.keys.each do |key| self.send("#{key}=", options[key] || defaults[key]) end end end module Associatable # Phase IIIb def belongs_to(name, options = {}) self.assoc_options[name] = BelongsToOptions.new(name, options) #use define_method (name) to create association method with name define_method(name) do associations_options = self.class.assoc_options[name] #send gets :foreign_key #model_class gets :class_name #Use "where" to select models where the #:primary_key column is equal to the foreign key value. fkey_val = self.send(associations_options.foreign_key) associations_options.model_class .where(associations_options.primary_key => fkey_val).first #return the instance of the object with matching primary key end end def has_many(name, options = {}) self.assoc_options[name] = HasManyOptions.new(name, self.name, options) #stores the object type of association options in assoc_options #creates an association method with (name) define_method(name) do associations_options = self.class.assoc_options[name] #access primary key pkey_val = self.send(associations_options.primary_key) associations_options .model_class .where(associations_options.foreign_key => pkey_val) #returns array of all instances of name objects end end def assoc_options #key = assoc object name. #value = new association object with data @assoc_options ||= {} @assoc_options end end class SQLObject extend Associatable end
require 'rails_helper' RSpec.describe "action_requireds/edit", type: :view do before(:each) do @action_required = assign(:action_required, ActionRequired.create!( name: "MyString", phone: "MyString", address: "MyString", category: "MyString", ref_number: "MyString", remarks: "MyText" )) end it "renders the edit action_required form" do render assert_select "form[action=?][method=?]", action_required_path(@action_required), "post" do assert_select "input[name=?]", "action_required[name]" assert_select "input[name=?]", "action_required[phone]" assert_select "input[name=?]", "action_required[address]" assert_select "input[name=?]", "action_required[category]" assert_select "input[name=?]", "action_required[ref_number]" assert_select "textarea[name=?]", "action_required[remarks]" end end end
class SecretCodeController < ApplicationController load_and_authorize_resource :class => "SecretCodes" #show all secrets codes #scope-> action handling def index @secret_codes = SecretCodes.includes(:user).all end def create strong_params = secret_code_params SecretCodes.create_codes strong_params[:count].to_i flash[:now] = strong_params[:count]+" secret code created successfully" redirect_to :back end private def secret_code_params params.permit(:count) end end
require File.dirname(__FILE__) + '/spec_helper.rb' describe "Client" do it "should instantiate a client with a username and password" do c = PostalMethods::Client.new(PM_OPTS) c.class.should == PostalMethods::Client end it "should fail without a user/pass on instantiation" do lambda {PostalMethods::Client.new()}.should raise_error(PostalMethods::NoCredentialsException) end it "should create a driver client thru the factory" do c = PostalMethods::Client.new(PM_OPTS) c.prepare! c.rpc_driver.class.should == SOAP::RPC::Driver end it "should raise a connection error exception when the api is unreachable" do c = PostalMethods::Client.new(PM_OPTS) c.stubs(:api_uri).returns("http://invaliduri.tld/api_endpoint.wtf?") lambda {c.prepare!}.should raise_error(PostalMethods::NoConnectionError) end it "should be able to set a work mode" do c = PostalMethods::Client.new(PM_OPTS) c.work_mode.should == "Default" c.work_mode = "ProdUCTion" c.work_mode.should == "Production" c.work_mode.should be_a_kind_of(String) end end
require 'rails_helper' describe Merchant, type: :model do let(:customer) {Customer.create(first_name: "Jorge", last_name: "Mexican", created_at: "2020-12-12 12:12:12", updated_at: "2020-12-11 12:12:12")} let(:merchant) {Merchant.create(name: "Jalapenos", created_at: "2012-03-27 14:54:09", updated_at: "2012-03-27 14:54:09")} let(:invoice) {Invoice.create(customer_id: customer.id, merchant_id: merchant.id, status: "shipped", created_at: "2020-12-12 12:12:12", updated_at: "2020-12-11 12:12:12")} let(:invoice2) {Invoice.create(customer_id: customer.id, merchant_id: merchant.id, status: "shipped", created_at: "2020-01-12 12:12:12", updated_at: "2020-01-11 12:12:12")} let(:item) {Item.create(name: "Tacos", description: "deliciosa", unit_price: 10, created_at: "2020-12-12 12:12:12", updated_at: "2020-12-11 12:12:12", merchant_id: merchant.id) } let(:invoice_item) {InvoiceItem.create item_id: item.id, invoice_id: invoice.id, quantity:10, unit_price: 100 } let(:invoice_item2) {InvoiceItem.create item_id: item.id, invoice_id: invoice2.id, quantity:10, unit_price: 100 } let(:transaction) { Transaction.create invoice_id: invoice.id, credit_card_number: "1010101010", result: "success"} let(:transaction2) { Transaction.create invoice_id: invoice.id, credit_card_number: "1010101010", result: "failed"} before(:each) do customer merchant invoice invoice2 item invoice_item invoice_item2 transaction transaction2 end it 'should have many invoices' do expect(merchant.invoices.include?(invoice)).to be(true) expect(merchant.invoices.count).to eq(2) end it 'should have many items' do expect(merchant.items.include?(item)).to be(true) expect(merchant.items.count).to be(1) end it 'should return most revenue for x items' do params = {quantity: "1"} expect(Merchant.most_rev(params).first).to eq(merchant) end it 'returns customers with pending invoices' do expect(merchant.customers_with_pending_invoices.first).to eq(customer) end end
require_relative("../db/sql_runner.rb") require_relative("animal") class Owner attr_reader :id attr_accessor :name, :notes, :phone_number def initialize(options) @name = options['name'] @id = options['id'].to_i if options['id'] @notes = options['notes'] @phone_number = options['phone_number'] end def save() sql = "INSERT INTO owners (name,notes,phone_number) VALUES ($1,$2,$3) RETURNING id;" values = [@name,@notes,@phone_number] result = SqlRunner.run(sql,values) @id = result.first()['id'].to_i end def update() sql = "UPDATE owners SET name = $1,notes=$2,phone_number=$4 WHERE id=$3" values = [@name,@notes,@id,@phone_number] SqlRunner.run(sql,values) end def delete() sql = "DELETE * FROM owners WHERE id=$1" values = [@id] SqlRunner.run(sql,values) end def animals() sql = "SELECT * FROM animals WHERE owner_id=$1" values = [@id] result = SqlRunner.run(sql,values) animals = result.map{|x| Animal.new(x)} return animals end def self.delete_by_id(id) sql = "DELETE FROM owners WHERE id=$1" values = [id] SqlRunner.run(sql,values) end def self.all() sql = "SELECT * FROM owners" result = SqlRunner.run(sql) return result.map{|x| Owner.new(x)} end def self.find_by_id(id) sql = 'SELECT * FROM owners WHERE id=$1' values = [id] result = SqlRunner.run(sql,values) return Owner.new(result.first) end def self.delete_all() sql = 'DELETE FROM owners' SqlRunner.run(sql) end end
class Trade::BatchUpdate def initialize(search_params) search = Trade::Filter.new(search_params) @shipments = Trade::Shipment.joins( <<-SQL JOIN ( #{search.query.to_sql} ) q ON q.id = trade_shipments.id SQL ) end def execute(update_params) affected_shipments = nil Trade::Shipment.transaction do affected_shipments = @shipments.count @shipments.update_all(update_params) DownloadsCache.clear_shipments end affected_shipments end end
Rails.application.routes.draw do root 'test#test' post '/posttest', to:'test#post' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
require_relative 'Randomizer' class Die < Randomizer attr_reader :sides def initialize(sides_input,colour_input) @enum_colour = [:red,:green,:blue,:yellow,:black,:white] if sides_input < 3 return nil end colour_flag = false for i in (0..@enum_colour.size-1) if colour_input == @enum_colour[i] colour_flag = true end end if colour_flag == false return nil end @colour = colour_input @item = :die @sides = sides_input @up = nil @randomizations = 0 end def colour() return(@colour) end def sides() return(@sides) end def roll() randomize() end def side_up() result() end end
#-- # ============================================================================= # Copyright (c) 2004, Jamis Buck (jamis@37signals.com) # All rights reserved. # # This source file is distributed as part of the Needle dependency injection # library for Ruby. This file (and the library as a whole) may be used only as # allowed by either the BSD license, or the Ruby license (or, by association # with the Ruby license, the GPL). See the "doc" subdirectory of the Needle # distribution for the texts of these licenses. # ----------------------------------------------------------------------------- # needle website : http://needle.rubyforge.org # project website: http://rubyforge.org/projects/needle # ============================================================================= #++ $:.unshift "../../lib" require 'needle/pipeline/element' require 'test/unit' class TC_Pipeline_Element < Test::Unit::TestCase def test_default_priority assert_equal 0, Needle::Pipeline::Element.default_priority element = Needle::Pipeline::Element.new nil assert_equal Needle::Pipeline::Element.default_priority, element.priority end def test_default_name element = Needle::Pipeline::Element.new nil assert_nil element.name end def test_name element = Needle::Pipeline::Element.new nil, :test assert_equal :test, element.name end def test_priority element = Needle::Pipeline::Element.new nil, :test, 50 assert_equal 50, element.priority end def test_index_operator element = Needle::Pipeline::Element.new nil assert_raise( NotImplementedError ) { element[:arg] } end def test_call element = Needle::Pipeline::Element.new nil assert_raise( NotImplementedError ) { element.call( :arg ) } end def test_ordering element1 = Needle::Pipeline::Element.new( nil, :test1, 25 ) element2 = Needle::Pipeline::Element.new( nil, :test2, 75 ) assert_equal( -1, element1 <=> element2 ) assert_equal( 1, element2 <=> element1 ) end def test_comparable element1 = Needle::Pipeline::Element.new( nil, :test1, 25 ) element2 = Needle::Pipeline::Element.new( nil, :test2, 75 ) assert element1 < element2 assert element2 > element1 assert element1 != element2 end end
# Removing full vs. rating distinction as part of the RIC project # These columns are no longer needed as they serve no purpose going forward. class DropDeprecatedFullRatingColumns < ActiveRecord::Migration def self.up remove_column :product_stats, :active_full_review_count remove_column :product_stats, :active_rating_review_count remove_column :user_stats, :full_review_count remove_column :user_stats, :rating_review_count end def self.down raise ActiveRecord::IrreversibleMigration end end
class ConversationsChannel < ApplicationCable::Channel def subscribed #createing a generic channel where all users connect # stream_from "conversations_channel" # creating a private channel for each user stream_from "current_user_#{current_user.id}" end def unsubscribed # Any cleanup needed when channel is unsubscribed end end
class AddMagicAttributesToActiveAdminAssets < ActiveRecord::Migration def change add_column :active_admin_assets, :storage_width, :integer add_column :active_admin_assets, :storage_height, :integer add_column :active_admin_assets, :storage_aspect_ratio, :float add_column :active_admin_assets, :storage_depth, :integer add_column :active_admin_assets, :storage_format, :string add_column :active_admin_assets, :storage_mime_type, :string add_column :active_admin_assets, :storage_size, :string end end
class Workflow::AccrualKey < ApplicationRecord belongs_to :workflow_accrual_job, class_name: 'Workflow::AccrualJob', foreign_key: 'workflow_accrual_job_id' has_one :workflow_globus_transfer, class_name: 'Workflow::GlobusTransfer', dependent: :destroy, foreign_key: 'workflow_accrual_key_id' def exists_on_main_root? source_root, source_prefix = workflow_accrual_job.staging_root_and_prefix StorageManager.instance.main_root.exist?("#{source_prefix}/#{self.key}") end def self.exists_on_main_root select { |workflow_accrual_key| workflow_accrual_key.exists_on_main_root?} end def self.copy_not_requested where(copy_requested: false) end def self.copy_requested where(copy_requested: true) end def self.has_error where('error IS NOT NULL') end end
class SessionsController < ApplicationController def new end def create @user = User.find_by_credentials(user_params[:email], user_params[:password]) return nil if @user.nil? login! @user redirect_to user_url(@user) end def destroy logout! redirect_to new_session_url end private def user_params params[:user].permit(:email, :password) end end
require 'spec_helper' describe Launchpad::Settings do let(:settings_fixture) { 'spec/fixtures/config/settings.yml' } let(:settings_path) { 'spec/fixtures/config/current-settings.yml' } before do FileUtils.copy settings_fixture, settings_path stub_const 'Launchpad::Settings::PATH', settings_path end after do File.delete settings_path end describe '.read' do it 'should access saved settings' do expect(described_class.read :install) .to eq 'test/install' expect(described_class.read :login_server) .to eq 'http://login.example.com/' end end describe '.update' do it 'should update a given settings value' do expect { described_class.update :install, 'test/updated' } .to change { described_class.read :install } .from('test/install') .to('test/updated') end end describe '.save' do before do described_class.update :install, 'test/updated' described_class.save end it 'should update the yaml file with new values' do expect(described_class.clone.read :install) .to eq 'test/updated' end end end
require File.expand_path(File.dirname(__FILE__) + "/test_helper") class JobTest < Test::Unit::TestCase context "A Job" do should "output the :task" do job = new_job(:template => ":task", :task => 'abc123') assert_equal %q(abc123), job.output end should "output the :task if it's in single quotes" do job = new_job(:template => "':task'", :task => 'abc123') assert_equal %q('abc123'), job.output end should "output the :task if it's in double quotes" do job = new_job(:template => '":task"', :task => 'abc123') assert_equal %q("abc123"), job.output end should "output escaped single quotes in when it's wrapped in them" do job = new_job( :template => "before ':foo' after", :foo => "quote -> ' <- quote" ) assert_equal %q(before 'quote -> '\'' <- quote' after), job.output end should "output escaped double quotes when it's wrapped in them" do job = new_job( :template => 'before ":foo" after', :foo => 'quote -> " <- quote' ) assert_equal %q(before "quote -> \" <- quote" after), job.output end should "act reasonable in edge cases" do foo = %(quotes -> '" <- quotes) job = new_job( :template => %(before ':foo" between ":foo' after), :foo => foo ) assert_equal %(before '#{foo}" between "#{foo}' after), job.output end end private def new_job(options) Whenever::Job.new(options) end end
require 'hashie' module SimplyGenius module Atmos class SettingsHash < Hashie::Mash include GemLogger::LoggerSupport include Hashie::Extensions::DeepMerge include Hashie::Extensions::DeepFetch disable_warnings PATH_PATTERN = /[\.\[\]]/ def notation_get(key) path = key.to_s.split(PATH_PATTERN).compact path = path.collect {|p| p =~ /^\d+$/ ? p.to_i : p } result = nil begin result = deep_fetch(*path) rescue Hashie::Extensions::DeepFetch::UndefinedPathError => e logger.debug("Settings missing value for key='#{key}'") end return result end def notation_put(key, value, additive: true) path = key.to_s.split(PATH_PATTERN).compact path = path.collect {|p| p =~ /^\d+$/ ? p.to_i : p } current_level = self path.each_with_index do |p, i| if i == path.size - 1 if additive && current_level[p].is_a?(Array) current_level[p] = current_level[p] | Array(value) else current_level[p] = value end else if current_level[p].nil? if path[i+1].is_a?(Integer) current_level[p] = [] else current_level[p] = {} end end end current_level = current_level[p] end end def self.add_config(yml_file, key, value, additive: true) orig_config_with_comments = File.read(yml_file) comment_places = {} comment_lines = [] orig_config_with_comments.each_line do |line| line.gsub!(/\s+$/, "\n") if line =~ /^\s*(#.*)?$/ comment_lines << line else if comment_lines.present? comment_places[line.chomp] = comment_lines comment_lines = [] end end end comment_places["<EOF>"] = comment_lines orig_config = SettingsHash.new((YAML.load_file(yml_file) rescue {})) orig_config.notation_put(key, value, additive: additive) new_config_no_comments = YAML.dump(orig_config.to_hash) new_config_no_comments.sub!(/\A---\n/, "") new_yml = "" new_config_no_comments.each_line do |line| line.gsub!(/\s+$/, "\n") cline = comment_places.keys.find {|k| line =~ /^#{k}/ } comments = comment_places[cline] comments.each {|comment| new_yml << comment } if comments new_yml << line end comment_places["<EOF>"].each {|comment| new_yml << comment } return new_yml end end end end
# frozen_string_literal: true namespace :db do desc 'It updates every user access token' task update_token: :environment do User.all.each { |user| AccessTokenRefresher.new(user).call } end end
class Producer < ApplicationRecord has_one :appellation has_one :country, :through => :appellation has_many :wines end
class AdminsController < ApplicationController before_action :authenticate_user! before_action :require_admin def index @users = [] @editors = [] end def add_editor_admin if params[:q] if params[:q].blank? params[:q] = "@" end @users = User.search(params[:q]) else @users = [] end end def view_editor_admin @editors = User.where(editor: true) @admins = User.where(admin: true) @rows = [@editors.length, @admins.length].max end def remove_admin user = User.find(params[:id]) user.admin = false if user.save redirect_to view_editor_admin_path, flash: { success: "#{user.email} is no longer an Administrator." } else flash[:error] = "Error: There was a problem removing the rights." render :view_editor_admin end end def remove_editor user = User.find(params[:id]) user.editor = false if user.save redirect_to view_editor_admin_path, flash: { success: "#{user.email} is no longer an Editor." } else flash[:error] = "Error: There was a problem removing the rights." render :view_editor_admin end end def add_editor user = User.find(params[:id]) user.editor = true if user.save redirect_to add_editor_admin_path(q: params[:q]), flash: { success: "#{user.email} is now an Editor." } else flash[:error] = "Error: There was a problem adding the rights." render :add_editor_admin end end def add_admin user = User.find(params[:id]) user.admin = true if user.save redirect_to add_editor_admin_path(q: params[:q]), flash: { success: "#{user.email} is now an Administrator." } else flash[:error] = "Error: There was a problem adding the rights." render :add_editor_admin end end private def require_admin unless current_user.admin == true redirect_to root_path, flash: { error: "You are not authorized to perform that action." } end end end
require_relative './topten' describe '#sanitize' do it 'should remove punctuation' do expect(sanitize('test!')).to eq 'test' end it 'should normalize to lowercase' do expect(sanitize('Test!')).to eq 'test' end end describe '#break_line' do it 'should count words in a string of text' do expected = {"this"=>2, "is"=>1, "a"=>1, "test"=>2} expect(break_line("This is a test THIS! TEST!")).to eq expected end end describe '#topten' do it 'should sort the hash by top values' do expected = {"this"=>2, "test"=>2, "is"=>1, "a"=>1} expect(topten({"this"=>2, "is"=>1, "a"=>1, "test"=>2})).to eq expected end it 'should return only top ten results' do expected = {"eleven"=>11, "ten"=>10, "nine"=>9, "eight"=>8, "seven"=>7, "six"=>6, "five"=>5, "four"=>4, "three"=>3, "two"=>2} expect(topten({"eleven"=>11, "ten"=>10, "nine"=>9, "eight"=>8, "seven"=>7, "six"=>6, "five"=>5, "four"=>4, "three"=>3, "two"=>2, "one"=>1})).to eq expected end end
require 'rails_helper' describe 'user deletes an article' do describe 'they link from the show page' do it 'displays all articles without the deleted article' do article_3 = Article.create!(title: "Title 3", body: "Body 3") article_2 = Article.create!(title: "Title 2", body: "Body 2") visit article_path(article_3) click_link "Delete" expect(current_path).to eq(articles_path) expect(page).to have_content(article_2.title) expect(page).to_not have_content(article_3.title) end end end
class ExampleController < ApplicationController def example1 # Explicit Render: # # We can specify the specific file we want to render # and send back to the browser render '/example/explicit_render' end def example2 # Implicit Render: # # Rails can guess the name based on the controller and action: # # This renders the file /example/example2.html.erb # It finds this file by looking at the controller name ("ExampleController") # and the action name ("example2") render end def example3 # Passing Data to View # # When we want the view to render some data # we can pass the information using an instance variable # # Look at the file "views/example/example3.html.erb" to # see how this hash is used @vending_machine_hash = { 'D0' => "Pop Tarts - Smores", 'D2' => "Pop Tarts - Strawberry", 'D4' => "Pop Tarts - Strawberry", 'D6' => "Rice Crispy Treats", 'D8' => "Reese's Pieces" } # We don't even need the render, rails will # automagically render the correct file end def image_example @image_num = rand(0..9) end def background_image_example @image_num = rand(0..9) end def rails_magic_example render plain: "MAGIC!!!" end end
if @user.valid? json.set! :result, :success else response.status = 400 json.set! :result, :error end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception # Antes de qualquer ação, o usuário precisa estar logado before_action :require_login private def require_login unless logged_in? flash[:notice] = "Você precisa estar logado." redirect_to '/sign_in' # halts request cycle end end def logged_in? session[:user_id] end def current_user if session[:user_id] Usuario.find(session[:user_id]) else nil end end end
raise 'Wrong number of arguments' unless ARGV.length >= 2 && ARGV.length <= 3 steam_id = SteamId.to_64(ARGV[0]) raise 'Invalid steam id' unless steam_id username = ARGV[1] raise 'Empty username' if username.empty? terminated_at = Time.zone.now + ActiveSupport::Duration.parse(ARGV[2]) if ARGV.length == 3 # Find the user or create them if they don't exist u = User.find_by(steam_id: steam_id) puts 'Banning existing user' if u u ||= User.create!(steam_id: steam_id, name: username) # Ban from everything u.ban(:use, :users, terminated_at: terminated_at) u.ban(:use, :teams, terminated_at: terminated_at) u.ban(:use, :leagues, terminated_at: terminated_at) u.ban(:use, :forums, terminated_at: terminated_at) puts "Banned user #{u.id}"
class CreateImages < ActiveRecord::Migration def change create_table :images do |t| t.references :folder t.string :title t.string :alternative t.text :description t.string :image_file_name t.string :image_content_type t.integer :image_file_size t.integer :order_of_display t.datetime :opened_at t.datetime :closed_at t.integer :created_by_id t.integer :updated_by_id t.timestamps end end end
class Matrons::RegistrationsController < Matrons::ApplicationController skip_before_action :authenticate_user!, only: %i(new create) def new render_view Matrons::Registrations::New, matron_create: nil end def create matron_create = Matron::Create.run(hparams.fetch(:matron_create, {})) if matron_create.success? sign_in(matron_create.result) redirect_to matrons_signed_in_root_path else render_view Matrons::Registrations::New, matron_create: matron_create end end end
require "rails_helper" describe Tag do let(:repo) { Repository.new(name: "test/hello-world") } describe ".find" do let(:name) { "latest" } context "with a repository returning non-json content type for meta blob" do let(:blob_content_type) { "application/octet-stream" } it "returns one repository" do VCR.use_cassette("tag/find", erb: {blob_content_type: blob_content_type}) do tag = Tag.find repository: repo, name: name expect(tag).to be_instance_of Tag end end end context "with a repository returning json content type for meta blob" do let(:blob_content_type) { "application/vnd.docker.container.image.v1+json" } it "returns one repository" do VCR.use_cassette("tag/find", erb: {blob_content_type: blob_content_type}) do tag = Tag.find repository: repo, name: name expect(tag).to be_instance_of Tag end end end end describe "#delete" do let(:name) { "delete-me" } it "returns true" do VCR.use_cassette("tag/delete") do tag = Tag.find repository: repo, name: name expect(tag.delete).to be true end end end end
require 'concurrent' class ConcurrencySimulation def initialize @processes = [] if block_given? yield self run end end def add_process(&block) @processes << Process.new.tap do |p| p.instance_eval(&block) end end def processes_count @processes.length end def run barrier = Concurrent::CyclicBarrier.new(processes_count) latch = Concurrent::CountDownLatch.new(processes_count) max_blocks = @processes.map(&:blocks_count).max @processes.each do |p| p.async.run(max_blocks, barrier, latch) end latch.wait end class Process include Concurrent::Async class Context end def initialize @blocks = [] end def blocks_count @blocks.length end def _(&block) block ||= proc { } @blocks << block end def run(max_count, barrier, latch) context = Context.new barrier.wait @blocks.each do |block| context.instance_eval(&block) barrier.wait end (max_count - blocks_count).times do barrier.wait end latch.count_down end end end
require 'authenticate/callbacks/lifetimed' module Authenticate module Model # # Imposes a maximum allowed lifespan on a user's session, after which the session is expired and requires # re-authentication. # # = Configuration # Set the maximum session lifetime in the initializer, giving a timestamp. # # Authenticate.configure do |config| # config.max_session_lifetime = 8.hours # end # # If the max_session_lifetime configuration parameter is nil, the :lifetimed module is not loaded. # # = Columns # * current_sign_in_at - requires `current_sign_in_at` column. This column is managed by the :trackable plugin. # # = Methods # * max_session_lifetime_exceeded? - true if the user's session has exceeded the max lifetime allowed # # module Lifetimed extend ActiveSupport::Concern def self.required_fields(_klass) [:current_sign_in_at] end # Has the session reached its maximum allowed lifespan? def max_session_lifetime_exceeded? return false if max_session_lifetime.nil? return false if current_sign_in_at.nil? current_sign_in_at <= max_session_lifetime.ago end private def max_session_lifetime Authenticate.configuration.max_session_lifetime end end end end
FactoryBot.define do factory :forums_topic, class: 'Forums::Topic' do parent { nil } association :created_by, factory: :user locked { false } pinned { false } hidden { false } isolated { false } default_hidden { false } description { 'a *sample* description' } name { 'General Discussions' } end end
class Answer < ApplicationRecord belongs_to :question scope :correct_answers, -> { where(correct: true) } validates :body, presence: true validate :validate_count_answer, on: create private def validate_count_answer errors.add(:question, 'Ошибка. Ответов > 4') if question.answers.count >= 4 end end
require "rails_helper" describe StaticPagesController do let(:user) { build_with_attributes(User) } context "#email_sent" do before { user.save } it "assigns @user" do get :email_sent, id: user.id, email: user.email expect(assigns[:user]).to be_instance_of(User) end it_behaves_like "redirects_to_home_page_when_signed_in" do let(:action) { get :sign_in } end end context "#home" do it_behaves_like "require_sign_in" do let(:action) { get :home } end end context "#sign_in" do it "sets flash success message on email confirmation" do get :sign_in, email: Faker::Internet.email, email_confirmed: true expect(flash[:success]).to be_present end it "does not set flash success message w/o email confirmation" do get :sign_in expect(flash[:success]).not_to be_present end it_behaves_like "redirects_to_home_page_when_signed_in" do let(:action) { get :sign_in } end end context "#sign_up" do it "assigns @user" do get :sign_up expect(assigns[:user]).to be_instance_of(User) end it_behaves_like "redirects_to_home_page_when_signed_in" do let(:action) { get :sign_up } end end end
class AdminPortfolioSerializer < ActiveModel::Serializer attributes :id, :user_id, :market_value, :in_balance, :created_at def market_value # Report no value if they haven't set up yet..... object.current_shares.present? ? object.send(:current_market_value) : 0.0 end def in_balance # Report in balance if they haven't set up yet.... object.current_shares.present? ? object.out_of_balance?(0.05) : true end end
#!/usr/bin/ruby class String def lowercase? chars.all? do |c| !('A'..'Z').include?(c) end end def uppercase? chars.all? do |c| !('a'..'z').include?(c) end end end ALPHABET = [*'a'..'z'] TRANSLATIONS = ALPHABET.zip(ALPHABET.shuffle).to_h def translate(string) string.chars.map do |c| if TRANSLATIONS.include? c if c.lowercase? TRANSLATIONS[c] else TRANSLATIONS[c.downcase].upcase end else c end end.join end ARGF.each_line do |line| puts translate(line) end
Registrar::Engine.routes.draw do root "sessions#new" get "/auth/google/callback", to: "sessions#create" get "/signin", to: "sessions#new" get "/signout", to: "sessions#destroy" resource :sessions, only: [:new, :create, :destroy] end
class RemoveUserRefFromPost < ActiveRecord::Migration[5.0] def change remove_column :posts, :user, :refernces end end
class Metasubservicio < ActiveRecord::Base include Compartido belongs_to :metaservicio has_many :servicios, :dependent => :destroy validates_presence_of :nombre, :message => "no puede ir vacío" validates_presence_of :metaservicio_id, :message => "no puede ir en blanco" # Necesario para poder obtener CSVs de éste modelo acts_as_reportable # Atributos de éste modelo presentes al momento de desplegar instancias de éste modelo def self.atributos ["nombre", "es_un_servicio_de_tipo"] end # Atributos cuyos valores relativos a cada instancia de éste modelo serán traducidos a código ruby en un archivo para exportar como copia de seguridad def self.atributos_exportables [:nombre] end def es_un_servicio_de_tipo metaservicio.nombre end end
Container.boot(:logger) do |container| start do SemanticLogger.application = 'stasi-bot' SemanticLogger.add_appender(io: STDOUT) container.register(:logger, SemanticLogger['stasi-bot']) end end
class CreateQuestionnaireReports < ActiveRecord::Migration def change create_table :questionnaire_reports do |t| t.string :title, null:false, limit:255 t.string :summary, null:false, limit:800 t.timestamps null: false end end end
#require 'date' class BloodOath attr_accessor :initiation_date, :follower, :cult @@all_oaths = [] def initialize (follower, cult, initiation_date = Date.today) @follower = follower @cult = cult if initiation_date.class == Date @initiation_date = "#{initiation_date}" else @initiation_date = initiation_date end @@all_oaths << self end def self.all @@all_oaths end def self.first_oath all.sort_by { |oath| oath.initiation_date } .first .follower end end
require "cat" RSpec.describe Cat do describe "#name" do it "is super excited about its name" do expect(Cat.new("Milo").name).to eq("Milo!!!") end end describe "#speak" do it "says meow" do expect(Cat.new("Ninetales").speak).to eq("meow") end end end
class Beer < ActiveRecord::Base has_many :users, through: :associations end
class CreateAnswers < ActiveRecord::Migration def change create_table :answers do |t| t.string :value t.references :reply, index: true, foreign_key: true t.references :item, index: true, foreign_key: true t.timestamps null: false end remove_column :replies, :answers, :jsonb end end
class CreateParkingLists < ActiveRecord::Migration def change create_table :parking_lists do |t| t.string :first_name t.string :last_name t.string :email t.integer :spot_number t.datetime :parked_on t.timestamps end end end
module LoremIpsumNearby class Config attr_writer :search_radius, :search_radius_unit, :data_file_path, :center_point, :result_sort_by, :result_data_keys # Matching customers within this radius def search_radius @search_radius ||= 100 end # Matching customers within the radius in units, default is :km # Available options are - # - :km for Kilometer # - :mi for Mile def search_radius_unit @search_radius_unit ||= :km end # Customer data file. Which must be - # - Text file (`data/customers.json`) # - one customer data per line, JSON-encoded. def data_file_path @data_file_path ||= "data/customers.json".freeze end # Center point to match the customer's coordinate ([lat,lon]) # The GPS coordinates for Berlin office are 52.508283, 13.329657 def center_point @center_point ||= [52.508283, 13.329657].freeze end # Matched customers sort by def result_sort_by @result_sort_by ||= "user_id".freeze end # default result data keys of the matched customer data def result_data_keys @result_data_keys ||= %w[user_id name].freeze end # required data keys in the customer data file def required_data_keys %w[user_id name latitude longitude] end end end
# frozen_string_literal: true FactoryBot.define do factory :address do line_1 { Faker::Address.street_address } locality { Faker::Address.city } administrative_area { Faker::Address.city } postal_code { Faker::Address.postcode } end end
class QueueItem < ActiveRecord::Base belongs_to :user belongs_to :video delegate :title, to: :video, prefix: :video delegate :category, to: :video validates_numericality_of :position, { only_integer: true } def rating review.rating if review end def rating=(new_rating) if review review.update_column(:rating, new_rating) else review = Review.new(user: user, video: video, rating: new_rating) review.save(validate: false) end end def category_name category.name end private def review @review ||= Review.where(user_id: user.id, video_id: video.id).first end end
class ChangeCompanyTimezoneDatatype < ActiveRecord::Migration def change change_column :companies , :time_zone , :string end end
# frozen_string_literal: true require "test_helper" require_relative "common" require "active_record" class PostgresqlAdapterTest < ActionCable::TestCase include CommonSubscriptionAdapterTest def setup database_config = { "adapter" => "postgresql", "database" => "activerecord_unittest" } ar_tests = File.expand_path("../../../activerecord/test", __dir__) if Dir.exist?(ar_tests) require File.join(ar_tests, "config") require File.join(ar_tests, "support/config") local_config = ARTest.config["connections"]["postgresql"]["arunit"] database_config.update local_config if local_config end ActiveRecord::Base.establish_connection database_config begin ActiveRecord::Base.connection rescue @rx_adapter = @tx_adapter = nil skip "Couldn't connect to PostgreSQL: #{database_config.inspect}" end super end def teardown super ActiveRecord::Base.clear_all_connections! end def cable_config { adapter: "postgresql" } end end
# Use this file to easily define all of your cron jobs. # # It's helpful, but not entirely necessary to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # Example: set :environment, "development" set :output, "/home/richard/Rails/football_predictions/log/cron_log.log" #Retrieve League Table every :day, :at => '12:20am' do rake "grab:league" end #Retrieve League fixtures every :day, :at => '12:20am' do rake "grab:fixtures" end
class Notebook < ActiveRecord::Base include PgSearch multisearchable :against => [:title, :description] validates :author_id, presence: true belongs_to( :author, :class_name => 'User', :foreign_key => :author_id, :primary_key => :id ) has_many :notes, dependent: :destroy end
if ENV['HEROKU'].present? keys = [:name, :hostname, :exception_notification_sender, :exception_notification_recipient, :mail__user_name, :mail__password, :mail__smtp__address, :mail__smtp__port, :mail__domain, :storage, :storage__s3_access, :storage__s3_secret, :mailchimp_key, :paypal__account ] APP_CONFIG = HashWithIndifferentAccess.new keys.each do |key| APP_CONFIG[key.to_s.split("__").join(".")] = ENV[key.to_s.upcase] end else APP_CONFIG = Hashie::Mash.new(YAML.load_file("#{Rails.root}/config/app.yml")[Rails.env]) end
require 'rails_helper' require 'dummy_opener' RSpec.describe Nordnet::NumbersParser do let(:dummy_opener) { DummyOpener.new } let(:page) { Nokogiri::HTML(dummy_opener.call('__key_values__')) } let(:parser) { described_class.new } let(:good_call) { parser.call(page) } it 'returns a StockDatum' do expect(good_call).to be_a(StockDatum) end it 'finds the pe' do expect(good_call.pe).to eq(-533.33) end it 'finds the ps' do expect(good_call.ps).to eq(59.11) end it 'finds the price' do expect(good_call.price).to eq(240.0) end it 'finds the revinue' do expect(good_call.revinue).to eq(-144048) end it 'finds the sales' do expect(good_call.sales).to eq(233600) end it 'finds the dividend' do expect(good_call.dividend).to eq(0) end it 'finds the debt' do expect(good_call.debt).to eq(123_534) end it 'finds the pb' do expect(good_call.pb).to eq(46.6) end end
class Tester class T1 def palindrome?(string) # first implementation # treat string as an array of characters # 1. check edge cases first # return false for non-strings and nil strings by checking length method # 2. remove non-alphabet characters from string # create a new string that will contain only letters from string # use POSIX bracket expression to add each letter to the new string # if string is empty (no letters to check), return false # 3. convert all letters to lowercase for comparison # 4. check eack pair of characters one at a time for matches # start at the two ends of the string # while string[i] and string[j] refer to different characters, make comparison # move i and j towards middle of string if letters match, else return false # middle character (when i == j) is not important in a palindrome # return true if all characters match return false if not string.respond_to?(:length) test_string = "" string.length.times { |char| ( test_string << string[char] ) if ( string[char] =~ /[A-Za-z]/ ) } return false if test_string.length == 0 test_string = test_string.downcase i = 0 j = test_string.length - 1 while i < j return false if not test_string[i] == test_string[j] i += 1 j -= 1 end return true end end class T2 def palindrome?(string) # second implementation # use "reverse" method to compare strings (palindrome iff string == reverse_string) # 1-3. process string in the same manner as before # 4. compare string with reverse string and return result return false if not string.respond_to?(:length) test_string = "" string.length.times { |char| test_string << string[char] if string[char] =~ /[A-Za-z]/ } return false if test_string.length == 0 test_string = test_string.downcase return test_string == test_string.reverse end end end
#--- # Excerpted from "Rails 4 Test Prescriptions", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/nrtest2 for more book information. #--- require 'rails_helper' describe ProjectPresenter do let(:project) { double(name: "Project Runway") } let(:presenter) { ProjectPresenter.new(project) } it "handles name with on time status" do allow(project).to receive(:on_schedule?).and_return(true) expect(presenter.name_with_status).to eq( "<span class='on_schedule'>Project Runway</span>") end it "handles name with behind schedule status" do allow(project).to receive(:on_schedule?).and_return(false) expect(presenter.name_with_status).to eq( "<span class='behind_schedule'>Project Runway</span>") end end
# 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: 'Emanuel', city: cities.first) Menu.destroy_all Category.destroy_all first_category = Category.create!(name: 'First course') main_category = Category.create!(name: 'Main course') drink_category = Category.create!(name: 'Drink') Menu.create!([ { title: 'Borsh', price: '70', category: first_category }, { title: 'Pizza', price: '200', category: first_category }, { title: 'Sushi', price: '180', category: first_category }, { title: 'Pasta', price: '230', category: main_category }, { title: 'Salad', price: '220', category: main_category }, { title: 'Big_bon', price: '120', category: main_category }, { title: 'Vodka', price: '666', category: drink_category }, { title: 'Coca-Cola', price: '50', category: drink_category }, { title: 'Green Tea', price: '10', category: drink_category } ])
require 'rails_helper' describe User, type: :model do describe 'validations' do it {should validate_presence_of :email} it {should validate_presence_of :api_key} it {should validate_presence_of :password} end describe 'instance_methods' do it '#create_key' do user = User.new( email: 'whatever@example.com', password: 'password' ) expect(user.create_key).to be_a(String) end end end
FactoryGirl.define do factory :task do name "Task01" status 0 description "A simple task." end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :sw_project_customer_qnax_role_access_right, :class => 'SwProjectCustomerQnax::RoleAccessRight' do user_role_id 1 action "MyString" resource "MyString" brief_note "MyString" last_updated_by_id 1 end end
class ResumevidsController < ApplicationController def create @member=Member.find(params[:member_id]) @resumevid=@member.resumevids.create(params[:resumevid]) respond_to do |format| if @resumevid.save format.html { redirect_to edit_member_path(@member), :notice => 'Video was successfully added.' } format.js else format.html { redirect_to edit_member_path(@member), :notice => 'Unprocessable video entry' } format.js { render :json => @resumevid.errors, :status => :unprocessable_entity } end end end def destroy @member = Member.find(params[:member_id]) @resumevid = @member.resumevids.find(params[:id]) @resumevid.destroy respond_to do |format| format.html { redirect_to member_path(@member) } format.js end end end
# == Schema Information # # Table name: appreciations # # id :bigint not null, primary key # project_id :integer not null # appreciator_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Appreciation < ApplicationRecord # --Appreciation Validations-- validates :project_id, uniqueness: { scope: :appreciator_id } # --Appreciation Associations-- belongs_to :project, primary_key: :id, foreign_key: :project_id, class_name: :Project belongs_to :appreciator, primary_key: :id, foreign_key: :appreciator_id, class_name: :User end
class AddPlanmodelToPlans < ActiveRecord::Migration[6.0] def change add_column :plans, :plan_content, :string add_column :plans, :plan_time, :integer end end
require_relative '../app/models/legislator' require_relative '../app/models/rep' require_relative '../app/models/sen' require_relative '../app/models/del' require_relative '../app/models/com' require 'csv' class SunlightLegislatorsImporter def self.import(filename) csv = CSV.new(File.open(filename), :headers => true) csv.each do |column| attributes = {} column.each do |field, value| # scrub value = nil if value == "" attributes[field.to_sym] = value end Legislator.create(attributes) end end end # IF YOU WANT TO HAVE THIS FILE RUN ON ITS OWN AND NOT BE IN THE RAKEFILE, UNCOMMENT THE BELOW # AND RUN THIS FILE FROM THE COMMAND LINE WITH THE PROPER ARGUMENT. # begin # raise ArgumentError, "you must supply a filename argument" unless ARGV.length == 1 # SunlightLegislatorsImporter.import(ARGV[0]) # rescue ArgumentError => e # $stderr.puts "Usage: ruby sunlight_legislators_importer.rb <filename>" # rescue NotImplementedError => e # $stderr.puts "You shouldn't be running this until you've modified it with your implementation!" # end
class Api::V1::RidesController < ApplicationController # Creates a new +Ride+ object, and update status of +CabStatus+. # Assign nearest cab to +Ride+. # # API: POST /rides/{pink, source_latitude, source_longitude, dest_latitude, _dest_longitude} # # @return [cab_number] The created +Ride+ def create cab = Cab.assign_nearest_cab(ride_params[:source_latitude], ride_params[:source_longitude],ride_params[:pink]) if cab @ride = Ride.new(ride_params.merge(cab_id: cab.id)) if @ride.save render json: {message: 'successfully created', cab_number: cab.vehicle_no}, status: :created end else render json: {message: 'cab not available'}, status: :failed end end # Update a new +Ride+ object, and update status of +CabStatus+. # Change Availabilty of cab +CabStatus+. # # API: PUT /rides/:id { dest_latitude, _dest_longitude, cab_id} # # @return [ride_cost] updated +Ride+ def update @ride = Ride.find(params[:id]) if @ride.update_attributes(complete_params.merge(end_at: Time.now)) @ride.change_availability @rent = @ride.calculate_rent render json: {message: 'successfully reached', ride_cost: @rent }, status: :completed end end private # Never trust parameters from the scary internet, only allow the white list through. def ride_params params.require(:ride).permit(:pink, :source_latitude, :source_longitude, :destination_latitude, :destination_longitude) end def complete_params params.require(:ride).permit(:id, :destination_latitude, :destination_longitude, :cab_id) end end
require 'rails_helper' describe Verify::AddressController do let(:user) { build(:user) } before do stub_verify_steps_one_and_two(user) end describe '#index' do it 'redirects if phone mechanism selected' do subject.idv_session.vendor_phone_confirmation = true get :index expect(response).to redirect_to verify_review_path end it 'redirects if usps mechanism selected' do subject.idv_session.address_verification_mechanism = 'usps' get :index expect(response).to redirect_to verify_review_path end it 'renders index if no mechanism selected' do get :index expect(response).to be_ok end end end
require 'base64' require 'iron_mq' # Backend for data pipeline that publishes to IronMQ # # Assumes the following env vars: # - IRON_TOKEN=MY_TOKEN # - IRON_PROJECT_ID=MY_PROJECT_ID module RailsPipeline::IronmqPublisher def self.included(base) base.send :include, InstanceMethods base.extend ClassMethods end module InstanceMethods def publish(topic_name, data) t0 = Time.now queue = _iron.queue(topic_name) queue.post({payload: Base64.strict_encode64(data)}.to_json) t1 = Time.now ::NewRelic::Agent.record_metric('Pipeline/IronMQ/publish', t1-t0) if RailsPipeline::HAS_NEWRELIC RailsPipeline.logger.debug "Publishing to IronMQ: #{topic_name} took #{t1-t0}s" end def _iron @iron = IronMQ::Client.new if @iron.nil? return @iron end end module ClassMethods end end
class Workshop < ApplicationRecord belongs_to :DateLookup belongs_to :Organization end
require 'rails/generators' require 'rails/generators/migration' class ActsAsTaggableMigrationGenerator < Rails::Generators::Base include Rails::Generators::Migration def self.source_root @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates')) end def self.next_migration_number(dirname) Time.now.strftime("%Y%m%d%H%M%S") end def create_migration migration_template "migration.rb", File.join("db/migrate", "#{file_name}.rb") end protected def file_name "acts_as_taggable_migration" end end
module Orocos # This is hardcoded here, as we need it to make sure people don't use # MQueues on systems where it is not available # # The comparison with the actual value from the RTT is done in # MQueue.available? TRANSPORT_MQ = 2 Port.transport_names[TRANSPORT_MQ] = 'MQueue' # Support for the POSIX Message Queues transport in RTT module MQueue # Returns true if the MQ transport is available on this system (i.e. # built in RTT) def self.available? if @available.nil? @available= if !defined?(RTT_TRANSPORT_MQ_ID) false elsif error = MQueue.try_mq_open Orocos.warn "the RTT is built with MQ support, but creating message queues fails with: #{error}" false elsif TRANSPORT_MQ != RTT_TRANSPORT_MQ_ID raise InternalError, "hardcoded value of TRANSPORT_MQ differs from the transport ID from RTT (#{TRANSPORT_MQ} != #{RTT_TRANSPORT_MQ_ID}. Set the value at the top of #{File.expand_path(__FILE__)} to #{RTT_TRANSPORT_MQ_ID} and report to the orocos.rb developers" else true end else @available end end class << self ## # :method:auto? # :call-seq: # Orocos::MQueue.auto? => true or false # Orocos::MQueue.auto = new_value # # If true, orocos.rb will try to use the MQ transport when # * the max sample size on the output port is known. If the port type # contains variable-sized containers, it means that # {Orocos::OutputPort#max_size} and/or OroGen::Spec::OutputPort#max_size # have been used on resp. the port object or the model that describes # it. # * it is known that the two involved tasks are on the same host (this # is possible only if orocos.rb is used to start the processes) # # It is false by default. Additionally, the Orocos::MQueue.warn? # predicate tells if a warning should be used for connections that can't # use MQ if MQueue.available? attr_predicate :auto?, true else def auto?; false end def auto=(value) if value raise ArgumentError, "cannot turn automatic MQ handling. It is either not built into the RTT, or you don't have enough permissions to create message queues (in which case a warning message has been displayed)" end end end ## # :method:warn? # :call-seq: # Orocos::MQueue.warn? => true or false # Orocos::MQueue.warn = new_value # # Controls whether orocos.rb should issue a warning if auto_use? is # true but some connection cannot use the message queues # # See the documentation of Orocos.auto_use? for the constraints on MQ # usage. attr_predicate :warn?, true ## # :method:auto_sizes? # :call-seq: # Orocos::MQueue.auto_sizes? => true or false # Orocos::MQueue.auto_sizes = new_value # # Controls whether orocos.rb should compute the required data size # for policies where MQ is used and data_size is 0. Turning it off # means that you rely on the component developpers to call # setDataSample in their components with a sufficiently big sample. # # See the documentation of Orocos.auto? for the constraints on MQ # usage. Setting this off and automatic MQ usage on is not robust # and therefore not recommended. attr_predicate :auto_sizes?, true ## # :method:validate_sizes? # :call-seq: # Orocos::MQueue.validate_sizes? => true or false # Orocos::MQueue.validate_sizes = new_value # # Controls whether orocos.rb should validate the data_size field in # the policies that require the use of MQ. If true, verify that this # size is compatible with the current operating systems limits, and # switch back to CORBA if it is not the case (or if the limits are # unknown). # # See the documentation of Orocos.auto? for the constraints on MQ # usage. Setting this off and automatic MQ usage on is not robust # and therefore not recommended. attr_predicate :validate_sizes?, true ## # :method:auto_fallback_to_corba? # :call-seq: # Orocos::MQueue.auto_fallback_to_corba? => true or false # Orocos::MQueue.auto_fallback_to_corba = new_value # # If true (the default), a failed connection that is using MQ will # only generate a warning, and a CORBA connection will be created # instead. # # While orocos.rb tries very hard to not create MQ connections if it # is not possible, it is hard to predict how much memory all # existing MQueues in a system take, which is bounded by per-user # limits or even by the amount of available kernel memory. # # If false, an exception is generated instead. attr_predicate :auto_fallback_to_corba?, true end @auto = false @auto_sizes = available? @validate_sizes = available? @warn = true @auto_fallback_to_corba = true # Verifies that the given buffer size (in samples) and sample size (in # bytes) are below the limits defined in /proc # # This is used by Port.handle_mq_transport if MQueue.validate_sizes? is # true. def self.valid_sizes?(buffer_size, data_size) if !msg_max || !msgsize_max Orocos.warn "the system-level MQ limits msg_max and msgsize_max parameters are unknown on this OS. I am disabling MQ support" return false end if buffer_size > msg_max msg = yield if block_given? Orocos.warn "#{msg}: required buffer size #{buffer_size} is greater than the maximum that the system allows (#{msg_max}). On linux systems, you can use /proc/sys/fs/mqueue/msg_max to change this limit" return false end if data_size > msgsize_max msg = yield if block_given? Orocos.warn "#{msg}: required sample size #{data_size} is greater than the maximum that the system allows (#{msgsize_max}). On linux systems, you can use /proc/sys/fs/mqueue/msgsize_max to change this limit" return false end return true end # Returns the maximum message queue size, in the number of samples def self.msg_max if !@msg_max.nil? return @msg_max end if !File.readable?('/proc/sys/fs/mqueue/msg_max') @msg_max = false else @msg_max = Integer(File.read('/proc/sys/fs/mqueue/msg_max').chomp) end end # Returns the maximum message size allowed in a message queue, in bytes def self.msgsize_max if !@msgsize_max.nil? return @msgsize_max end if !File.readable?('/proc/sys/fs/mqueue/msgsize_max') @msgsize_max = false else @msgsize_max = Integer(File.read('/proc/sys/fs/mqueue/msgsize_max').chomp) end end end end
require 'method_source' class DelayedWorker module Concern def add_job_into_delayed_worker( scheduled_at: nil, job_name: 'Delayed worker', subject_id: respond_to?(:id) ? id : nil, subject_type: self.class, params: {}, queue: 'default', backtrace: false, retry: 12, &block ) callback = block.source.split("\n")[1..-2].join("\n") delayed_worker = DelayedWorker.set(queue: queue, backtrace: backtrace, retry: binding.local_variable_get(:retry)) Logger.logger.info "#{job_name} is adding into queue #{queue}!" if scheduled_at.nil? # last arg pass in scheduled_at as nil, this means no delayed. delayed_worker.perform_async(job_name, subject_id, subject_type, callback, params, nil) # valid type: Time, DateTime, ActiveSupport::TimeWithZone or 5.minutes (a integer) elsif scheduled_at.respond_to?(:to_time) && scheduled_at.to_time.is_a?(Time) || scheduled_at.is_a?(Integer) delayed_worker.perform_in(scheduled_at, job_name, subject_id, subject_type, callback, params, scheduled_at.to_i) else Logger.logger.error "#{job_name} time invalid!" end end alias add_job_to_delayed_worker add_job_into_delayed_worker end ::ActiveRecord::Base.send(:include, Concern) if defined? ::ActiveRecord::Base ::ActionController::Base.send(:include, Concern) if defined? ::ActionController::Base end
# frozen_string_literal: true require File.expand_path('lib/divvyup/version') Gem::Specification.new do |s| s.name = 'divvyup' s.version = DivvyUp::VERSION s.summary = 'DivvyUp Worker Queue' s.description = 'A simple redis-based queue system designed for failure' s.authors = ['Jonathan Johnson'] s.email = 'jon@nilobject.com' s.files = `git ls-files`.split("\n") s.homepage = 'http://github.com/nilobject/divvyup' s.license = 'MIT' s.require_path = 'lib' s.add_development_dependency 'bundler', '>= 1.0.0' s.add_dependency 'redis' s.add_dependency 'semantic_logger' s.add_dependency 'json' end
json.array! @jobs do |job| json.extract! job, :id, :title, :total_pay, :spoken_languages end
class Category < ApplicationRecord validates :name, presence: true, length: { minimum: 3, maximum: 30 }, uniqueness: true has_many :sub_categories, dependent: :destroy end
class Topic < ApplicationRecord extend FriendlyId friendly_id :title, use: :slugged validates_presence_of :title #a data relationship is created by giving one data element the aspect of having many of another data element, as in the code line below, where we are saying that any topic will have many blogs attached to it. You can have dozens of blogs with the topic "Ruby Programming" has_many :blogs scope :with_blogs, -> {joins(:blogs).select("DISTINCT topics.*")} end
# encoding: utf-8 # Use this file to easily define all of your cron jobs. # # It's helpful, but not entirely necessary to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # Example: # # set :output, "/path/to/my/cron_log.log" # # every 2.hours do # command "/usr/bin/some_great_command" # runner "MyModel.some_method" # rake "some:great:rake:task" # end # # every 4.days do # runner "AnotherModel.prune_old_records" # end # update recipe_food_genre amount column every 1.hour do runner "RecipeFoodGenre.aggrigation" end # create today's popular recipe ranking every 1.day, at:"00:05" do runner "RecipeRanking.aggrigation" end # create today's popular recipe food ranking every 1.day, at:"00:10" do runner "RecipeFoodRanking.aggrigation" end every 1.day, at:"11:00" do # runner "MailBuffer.send_mail_buffers" end # caliculate today's entry and retire users amount every 1.day, at:"00:30" do runner "EntretResult.aggrigation" end every 1.day, at:"01:00" do runner "TrackerResult.aggrigation" end every 1.hour do runner "FacebookFriendInvite.invites" end every 1.day, at:"10:00" do runner "RecommendRecipeMail.send_mail_magazines" end # Learn more: http://github.com/javan/whenever
def letter_case_count(string) stat = {lowercase: 0, uppercase: 0, neither: 0} string.chars.each do |letter| case letter when /[a-z]/ stat[:lowercase] += 1 when /[A-Z]/ stat[:uppercase] += 1 else stat[:neither] += 1 end end return stat end puts letter_case_count('abCdef 123') == { lowercase: 5, uppercase: 1, neither: 4 } puts letter_case_count('AbCd +Ef') == { lowercase: 3, uppercase: 3, neither: 2 } puts letter_case_count('123') == { lowercase: 0, uppercase: 0, neither: 3 } puts letter_case_count('') == { lowercase: 0, uppercase: 0, neither: 0 }
class Post < ApplicationRecord has_one_attached :image belongs_to :category, optional: true belongs_to :user, optional: true has_many :adds has_many :users_added, through: :adds, source: :user end
module Square # WebhookSubscriptionsApi class WebhookSubscriptionsApi < BaseApi # Lists all webhook event types that can be subscribed to. # @param [String] api_version Optional parameter: The API version for which # to list event types. Setting this field overrides the default version used # by the application. # @return [ListWebhookEventTypesResponse Hash] response from the API call def list_webhook_event_types(api_version: nil) new_api_call_builder .request(new_request_builder(HttpMethodEnum::GET, '/v2/webhooks/event-types', 'default') .query_param(new_parameter(api_version, key: 'api_version')) .header_param(new_parameter('application/json', key: 'accept')) .auth(Single.new('global'))) .response(new_response_handler .deserializer(APIHelper.method(:json_deserialize)) .is_api_response(true) .convertor(ApiResponse.method(:create))) .execute end # Lists all webhook subscriptions owned by your application. # @param [String] cursor Optional parameter: A pagination cursor returned by # a previous call to this endpoint. Provide this to retrieve the next set of # results for your original query. For more information, see # [Pagination](https://developer.squareup.com/docs/build-basics/common-api-p # atterns/pagination). # @param [TrueClass | FalseClass] include_disabled Optional parameter: # Includes disabled [Subscription](entity:WebhookSubscription)s. By default, # all enabled [Subscription](entity:WebhookSubscription)s are returned. # @param [SortOrder] sort_order Optional parameter: Sorts the returned list # by when the [Subscription](entity:WebhookSubscription) was created with # the specified order. This field defaults to ASC. # @param [Integer] limit Optional parameter: The maximum number of results # to be returned in a single page. It is possible to receive fewer results # than the specified limit on a given page. The default value of 100 is also # the maximum allowed value. Default: 100 # @return [ListWebhookSubscriptionsResponse Hash] response from the API call def list_webhook_subscriptions(cursor: nil, include_disabled: false, sort_order: nil, limit: nil) new_api_call_builder .request(new_request_builder(HttpMethodEnum::GET, '/v2/webhooks/subscriptions', 'default') .query_param(new_parameter(cursor, key: 'cursor')) .query_param(new_parameter(include_disabled, key: 'include_disabled')) .query_param(new_parameter(sort_order, key: 'sort_order')) .query_param(new_parameter(limit, key: 'limit')) .header_param(new_parameter('application/json', key: 'accept')) .auth(Single.new('global'))) .response(new_response_handler .deserializer(APIHelper.method(:json_deserialize)) .is_api_response(true) .convertor(ApiResponse.method(:create))) .execute end # Creates a webhook subscription. # @param [CreateWebhookSubscriptionRequest] body Required parameter: An # object containing the fields to POST for the request. See the # corresponding object definition for field details. # @return [CreateWebhookSubscriptionResponse Hash] response from the API call def create_webhook_subscription(body:) new_api_call_builder .request(new_request_builder(HttpMethodEnum::POST, '/v2/webhooks/subscriptions', 'default') .header_param(new_parameter('application/json', key: 'Content-Type')) .body_param(new_parameter(body)) .header_param(new_parameter('application/json', key: 'accept')) .body_serializer(proc do |param| param.to_json unless param.nil? end) .auth(Single.new('global'))) .response(new_response_handler .deserializer(APIHelper.method(:json_deserialize)) .is_api_response(true) .convertor(ApiResponse.method(:create))) .execute end # Deletes a webhook subscription. # @param [String] subscription_id Required parameter: [REQUIRED] The ID of # the [Subscription](entity:WebhookSubscription) to delete. # @return [DeleteWebhookSubscriptionResponse Hash] response from the API call def delete_webhook_subscription(subscription_id:) new_api_call_builder .request(new_request_builder(HttpMethodEnum::DELETE, '/v2/webhooks/subscriptions/{subscription_id}', 'default') .template_param(new_parameter(subscription_id, key: 'subscription_id') .should_encode(true)) .header_param(new_parameter('application/json', key: 'accept')) .auth(Single.new('global'))) .response(new_response_handler .deserializer(APIHelper.method(:json_deserialize)) .is_api_response(true) .convertor(ApiResponse.method(:create))) .execute end # Retrieves a webhook subscription identified by its ID. # @param [String] subscription_id Required parameter: [REQUIRED] The ID of # the [Subscription](entity:WebhookSubscription) to retrieve. # @return [RetrieveWebhookSubscriptionResponse Hash] response from the API call def retrieve_webhook_subscription(subscription_id:) new_api_call_builder .request(new_request_builder(HttpMethodEnum::GET, '/v2/webhooks/subscriptions/{subscription_id}', 'default') .template_param(new_parameter(subscription_id, key: 'subscription_id') .should_encode(true)) .header_param(new_parameter('application/json', key: 'accept')) .auth(Single.new('global'))) .response(new_response_handler .deserializer(APIHelper.method(:json_deserialize)) .is_api_response(true) .convertor(ApiResponse.method(:create))) .execute end # Updates a webhook subscription. # @param [String] subscription_id Required parameter: [REQUIRED] The ID of # the [Subscription](entity:WebhookSubscription) to update. # @param [UpdateWebhookSubscriptionRequest] body Required parameter: An # object containing the fields to POST for the request. See the # corresponding object definition for field details. # @return [UpdateWebhookSubscriptionResponse Hash] response from the API call def update_webhook_subscription(subscription_id:, body:) new_api_call_builder .request(new_request_builder(HttpMethodEnum::PUT, '/v2/webhooks/subscriptions/{subscription_id}', 'default') .template_param(new_parameter(subscription_id, key: 'subscription_id') .should_encode(true)) .header_param(new_parameter('application/json', key: 'Content-Type')) .body_param(new_parameter(body)) .header_param(new_parameter('application/json', key: 'accept')) .body_serializer(proc do |param| param.to_json unless param.nil? end) .auth(Single.new('global'))) .response(new_response_handler .deserializer(APIHelper.method(:json_deserialize)) .is_api_response(true) .convertor(ApiResponse.method(:create))) .execute end # Updates a webhook subscription by replacing the existing signature key # with a new one. # @param [String] subscription_id Required parameter: [REQUIRED] The ID of # the [Subscription](entity:WebhookSubscription) to update. # @param [UpdateWebhookSubscriptionSignatureKeyRequest] body Required # parameter: An object containing the fields to POST for the request. See # the corresponding object definition for field details. # @return [UpdateWebhookSubscriptionSignatureKeyResponse Hash] response from the API call def update_webhook_subscription_signature_key(subscription_id:, body:) new_api_call_builder .request(new_request_builder(HttpMethodEnum::POST, '/v2/webhooks/subscriptions/{subscription_id}/signature-key', 'default') .template_param(new_parameter(subscription_id, key: 'subscription_id') .should_encode(true)) .header_param(new_parameter('application/json', key: 'Content-Type')) .body_param(new_parameter(body)) .header_param(new_parameter('application/json', key: 'accept')) .body_serializer(proc do |param| param.to_json unless param.nil? end) .auth(Single.new('global'))) .response(new_response_handler .deserializer(APIHelper.method(:json_deserialize)) .is_api_response(true) .convertor(ApiResponse.method(:create))) .execute end # Tests a webhook subscription by sending a test event to the notification # URL. # @param [String] subscription_id Required parameter: [REQUIRED] The ID of # the [Subscription](entity:WebhookSubscription) to test. # @param [TestWebhookSubscriptionRequest] body Required parameter: An object # containing the fields to POST for the request. See the corresponding # object definition for field details. # @return [TestWebhookSubscriptionResponse Hash] response from the API call def test_webhook_subscription(subscription_id:, body:) new_api_call_builder .request(new_request_builder(HttpMethodEnum::POST, '/v2/webhooks/subscriptions/{subscription_id}/test', 'default') .template_param(new_parameter(subscription_id, key: 'subscription_id') .should_encode(true)) .header_param(new_parameter('application/json', key: 'Content-Type')) .body_param(new_parameter(body)) .header_param(new_parameter('application/json', key: 'accept')) .body_serializer(proc do |param| param.to_json unless param.nil? end) .auth(Single.new('global'))) .response(new_response_handler .deserializer(APIHelper.method(:json_deserialize)) .is_api_response(true) .convertor(ApiResponse.method(:create))) .execute end end end
# Copyright 2016 OCLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'spec_helper' describe "the article record page" do before(:all) do url = 'https://authn.sd00.worldcat.org/oauth2/accessToken?authenticatingInstitutionId=128807&contextInstitutionId=128807&grant_type=client_credentials&scope=WorldCatDiscoveryAPI' stub_request(:post, url).to_return(:body => mock_file_contents("token.json"), :status => 200) end context "when displaying an article with an issue and volume (5131938809)" do before(:all) do stub_request(:get, "https://beta.worldcat.org/discovery/offer/oclc/5131938809?heldBy=OCPSB"). to_return(:status => 200, :body => mock_file_contents("offer_set_5131938809.rdf")) get '/catalog/5131938809' @doc = Nokogiri::HTML(last_response.body) end it "should display the title" do puts @doc xpath = "//h1[@id='bibliographic-resource-name'][text()='How Much Would US Style Fiscal Integration Buffer European Unemployment and Income Shocks? (A Comparative Empirical Analysis)']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the author" do author_name = @doc.xpath("//h2[@id='author-name']/a/text()") expect(author_name.to_s.gsub("\n", '').squeeze(' ').strip).to be == "Feyrer, James" end it "should display the contributors" do @contributors = @doc.xpath("//ul[@id='contributors']/li/span/a/text()") expect(@contributors.size).to eq(1) @contributors = @contributors.map {|contributor| contributor.to_s.gsub("\n", '').squeeze(' ').strip} expect(@contributors).to include("Sacerdote, Bruce") end it "should display the format" do xpath = "//span[@id='format'][text()='Article']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the language" do xpath = "//span[@id='language'][text()='English']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the publisher" do xpath = "//span[@property='schema:publisher']/span[@property='schema:name'][text()='American Economic Association']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the date published" do xpath = "//span[@property='schema:datePublished'][text()='2013-05-01']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the OCLC Number" do xpath = "//span[@property='library:oclcnum'][text()='5131938809']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right periodical name" do xpath = "//p[@id='citation']/span/span/span/span[@property='schema:name'][text()='American Economic Review']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right volume" do xpath = "//span[@property='schema:volumeNumber'][text()='103']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right issue" do xpath = "//span[@property='schema:issueNumber'][text()='3']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right start page" do xpath = "//span[@property='schema:pageStart'][text()='125']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right end page" do xpath = "//span[@property='schema:pageEnd'][text()='128']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the descriptions" do @descriptions = @doc.xpath("//p[@property='schema:description']/text()") expect(@descriptions.count).to eq(1) @descriptions = @descriptions.map {|description| description.to_s} File.open("#{File.expand_path(File.dirname(__FILE__))}/../text/5131938809_descriptions.txt").each do |line| expect(@descriptions).to include(line.chomp) end end end context "when displaying an article with no issue (204144725)" do before(:all) do stub_request(:get, "https://beta.worldcat.org/discovery/offer/oclc/204144725?heldBy=OCPSB"). to_return(:status => 200, :body => mock_file_contents("offer_set_204144725.rdf")) get '/catalog/204144725' @doc = Nokogiri::HTML(last_response.body) end it "should display the title" do title = @doc.xpath("//h1[@id='bibliographic-resource-name']/text()") expect(title.to_s.gsub("\n", '').squeeze(' ').strip).to be == "Van Gogh's Rediscovered Night Sky What brilliant celestial object did Vincent van Gogh include in his painting White House at Night?" end it "should display the author" do author_name = @doc.xpath("//h2[@id='author-name']/a/text()") expect(author_name.to_s.gsub("\n", '').squeeze(' ').strip).to be == "Olson, D. W." end it "should display the contributors" do @contributors = @doc.xpath("//ul[@id='contributors']/li/span/a/text()") expect(@contributors.size).to eq(1) @contributors = @contributors.map {|contributor| contributor.to_s.gsub("\n", '').squeeze(' ').strip} expect(@contributors).to include("Doescher, R. L.") end it "should display the format" do xpath = "//span[@id='format'][text()='Article']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the language" do xpath = "//span[@id='language'][text()='English']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the date published" do xpath = "//span[@property='schema:datePublished'][text()='2001']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the OCLC Number" do xpath = "//span[@property='library:oclcnum'][text()='204144725']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right periodical name" do xpath = "//p[@id='citation']/span/span/span[@property='schema:name'][text()='SKY AND TELESCOPE']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right volume" do xpath = "//span[@property='schema:volumeNumber'][text()='101']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right start page" do xpath = "//span[@property='schema:pageStart'][text()='34']" expect(@doc.xpath(xpath)).not_to be_empty end end context "when displaying an article with no issue or volume (777986070)" do before(:all) do stub_request(:get, "https://beta.worldcat.org/discovery/offer/oclc/777986070?heldBy=OCPSB"). to_return(:status => 200, :body => mock_file_contents("offer_set_777986070.rdf")) get '/catalog/777986070' @doc = Nokogiri::HTML(last_response.body) end it "should display the title" do xpath = "//h1[@id='bibliographic-resource-name'][text()='MapFAST a FAST geographic authorities mashup with Google Maps']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the author" do author_name = @doc.xpath("//h2[@id='author-name']/a/text()") expect(author_name.to_s.gsub("\n", '').squeeze(' ').strip).to be == "Rick Bennet" end it "should display the contributors" do @contributors = @doc.xpath("//ul[@id='contributors']/li/span/a/text()") expect(@contributors.size).to eq(4) @contributors = @contributors.map {|contributor| contributor.to_s.gsub("\n", '').squeeze(' ').strip} expect(@contributors).to include("OCLC Research.") expect(@contributors).to include("Edward T. O'Neill") expect(@contributors).to include("J. D. Shipengrover") expect(@contributors).to include("Kerre Kammerer") end it "should display the subjects" do @subjects = @doc.xpath("//ul[@id='subjects']/li/span/a/text()") expect(@subjects.count).to eq(2) @subjects = @subjects.map {|subject_value| subject_value.to_s} expect(@subjects).to include("Mashups (World Wide Web)--Library applications") expect(@subjects).to include("FAST subject headings") end it "should display the format" do xpath = "//span[@id='format'][text()='Article']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the language" do xpath = "//span[@id='language'][text()='English']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the OCLC Number" do xpath = "//span[@property='library:oclcnum'][text()='777986070']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right periodical name" do xpath = "//p[@id='citation']/span/span[@property='schema:name'][text()='Code4lib journal']" expect(@doc.xpath(xpath)).not_to be_empty end it "should have the right pagination" do xpath = "//span[@property='schema:pagination'][text()='issue 14 (July 25, 2011)']" expect(@doc.xpath(xpath)).not_to be_empty end it "should display the descriptions" do @descriptions = @doc.xpath("//p[@property='schema:description']/text()") expect(@descriptions.count).to eq(1) @descriptions = @descriptions.map {|description| description.to_s} File.open("#{File.expand_path(File.dirname(__FILE__))}/../text/777986070_descriptions.txt").each do |line| expect(@descriptions).to include(line.chomp) end end end end
class ChangeDefaultValueOfEnquiries < ActiveRecord::Migration def change change_column :enquiries, :boat_currency_rate, :float, default: 1 end end
class Company < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :requirements, dependent: :destroy has_many :events, dependent: :destroy has_many :employees, dependent: :destroy has_many :applicant_details, dependent: :destroy # validates :name, :phonenumber, :auth_code, presence: true validates :phonenumber, format: { with: /\A[-+]?[0-9]*\.?[0-9]+\Z/, message: "only allows numbers" }, allow_blank: true end
class Edge attr_reader :from, :to, :cost def initialize(from, to, cost) @from = from @to = to @cost = cost end def to_s "#{@from} ---> #{@to}, with #{@cost} weight." end end
class Category < ActiveRecord::Base has_many :products has_many :category_childs, class_name: 'Category', foreign_key: 'category_parent_id' belongs_to :category_parent, class_name: 'Category', foreign_key: 'category_parent_id' end
class CreateResourceSubwayLines < ActiveRecord::Migration def change create_table :resource_subway_lines do |t| t.references :resource, null: false t.references :subway_line, null: false t.timestamps end add_index :resource_subway_lines, :resource_id add_index :resource_subway_lines, :subway_line_id end end
require 'logger' require_relative 'private_gem_server/version' require_relative 'private_gem_server/server' require_relative 'private_gem_server/scanner' require_relative 'private_gem_server/sources' require_relative 'private_gem_server/sanity' module PrivateGemServer class << self attr_writer :logger def has(name, version) gem = gems[name] gem.include? version if gem end def add(file) @gems = nil Geminabox::GemStore.create Geminabox::IncomingGem.new File.open(file, 'rb') end def gems @gems ||= Dir["#{Geminabox.data}/gems/*.gem"].group_by { |x| x[%r{(\w+(-\D\w*)*)[^/]+$}, 1] }.map { |k, v| [k, v.map { |z| z[/(\d+[\.\d+]*)\.gem$/, 1] }] }.to_h end def logger @logger ||= Logger.new(STDOUT) end end end
class CreateMrclDetailRecords < ActiveRecord::Migration def change create_table :mrcl_detail_records do |t| t.integer :representative_number t.integer :representative_type t.integer :record_type t.integer :requestor_number t.string :policy_type t.integer :policy_number t.integer :business_sequence_number t.string :valid_policy_number t.string :manual_reclassifications t.integer :re_classed_from_manual_number t.integer :re_classed_to_manual_number t.string :reclass_manual_coverage_type t.date :reclass_creation_date t.string :reclassed_payroll_information t.date :payroll_reporting_period_from_date t.date :payroll_reporting_period_to_date t.float :re_classed_to_manual_payroll_total t.timestamps null: true end end end
class Product < ApplicationRecord belongs_to :supplier belongs_to :category has_many :images has_many :orders has_many :category_products has_many :categories, through: :category_products validates :name, presence: true def is_discounted? price <= 300 end def tax price * 0.09 end def total price + tax end # def images # Image.find_by(id: image_id) # end end
class Subscription < ApplicationRecord belongs_to :subscriber belongs_to :magazine end
#!/usr/bin/ruby require 'net/http' require 'digest' require 'uri' require 'openssl' require 'base64' require 'digest/md5' require 'rexml/document' class Create_Header def initialize(access_key, secret_key) @access_key = access_key @secret_key = secret_key end def create_sign_str(http_method,url,content_md5,content_type,params,canonicalized_amz_headers=nil) http_header_date = (Time.new - 8*3600).strftime('%a, %d %b %Y %H:%M:%S GMT') sign_param_list = Array[ http_method, content_md5, content_type, http_header_date ] if canonicalized_amz_headers != "" sign_param_list << canonicalized_amz_headers end sign_param_list << url return sign_param_list.join("\n") end def create_sign(method, path, params) canonicalized_amz_headers = "" if params.key?('x-amz-acl') canonicalized_amz_headers = "x-amz-acl:%s" % "#{params['x-amz-acl']}" end sign_str = create_sign_str( http_method=method, url=path, content_md5="#{params['content_md5']}", content_type="#{params['content_type']}", params="#{params['params']}", canonicalized_amz_headers=canonicalized_amz_headers ) sign = Base64.encode64(OpenSSL::HMAC.digest('sha1',@secret_key,sign_str)) return sign.rstrip end def generate_headers(method, path, params) request_date = (Time.new - 8*3600).strftime('%a, %d %b %Y %H:%M:%S GMT') sign = create_sign(method, path, params) authorization = "AWS" + " " + @access_key.to_s + ":" + sign header_data = Hash['Date' => request_date, 'Authorization' => authorization] if params.key?('x-amz-acl') header_data.update('x-amz-acl' => "#{params['x-amz-acl']}") end if params.key?('content_length') header_data.update('Content-Length' => "#{params['content_length']}") end header_data.update('Content-Type'=> "") if params.key?('content_type') header_data.update('Content-Type' => "#{params['content_type']}") end return header_data end end class Send_request < Create_Header @@host = "osc.speedycloud.net" def reqs(method,path,data,params) uri = URI.parse("http://"+@@host+path) http = Net::HTTP.new(uri.hostname) if method == "GET" resp, datas = http.get(path, generate_headers(method, path, params)) return resp.body end if method == "POST" resp = http.post(path, data=data, header=generate_headers(method, path, params)) return resp.body end if method == "PUT" resp = http.send_request("PUT",path,data=data,header=generate_headers(method, path, params)) return resp.body end if method == "DELETE" resp, datas = http.delete(path, generate_headers(method, path, params)) return resp.body end end def upload_big_data_put(method, path,data, params) uri = URI.parse("http://"+@@host+path) http = Net::HTTP.new(uri.hostname) resp = http.send_request("PUT",path,data=data,header=generate_headers(method, path, params)) return resp.header['etag'] end end class Object_storge < Send_request def get_path(path) base_path = "/" return "%s%s" % [base_path, path] end def list(bucket) =begin 查询桶内对象列表 参数: bucket: 桶名 注意: bucket参数为''时,可查看所有桶 =end rel_path = get_path bucket result = reqs "GET", rel_path, "none", {} return result end def create_bucket(bucket) =begin 创建存储桶 参数: bucket: 桶名 =end rel_path = get_path bucket result = reqs "PUT", rel_path, nil, {} return result end def delete_bucket(bucket) =begin 注意: 在桶内没有对象的时候才能删除桶 删除存储桶 参数: bucket: 桶名 =end rel_path = get_path bucket result = reqs "DELETE", rel_path, "none", {} return result end def query_backet_acl(bucket) =begin 查询桶的权限 参数: bucket: 桶名 =end rel_path = get_path "%s?acl" % bucket result = reqs "GET", rel_path, "none", {} return result end def query_object_acl(bucket, key) =begin 查询桶内对象的权限 参数: bucket: 桶名 key: 对象名 =end rel_path = get_path "%s/%s?acl" % [bucket, key] result = reqs "GET", rel_path, "none", {} return result end def delete_object_data(bucket, key) =begin 删除桶内非版本管理对象 注意: 删除成功不是返回200 参数: bucket: 桶名 key: 对象名 =end rel_path = get_path "%s/%s" % [bucket, key] result = reqs "DELETE", rel_path, "none", {} return result end def delete_versioning_object(bucket, key, versionId) =begin 删除桶内版本管理对象 参数: bucket: 桶名 key: 对象名 versionId: 对象名 =end rel_path = get_path "%s/%s?versionId=%s" % [bucket, key, versionId] result = reqs "DELETE", rel_path, "none", {} return result end def configure_versioning(bucket, status) =begin 设置版本控制 参数: bucket: 桶名 status: 状态("Enabled"或者"Suspended") =end rel_path = get_path "%s?versioning" % bucket versioningBody = '<?xml version="1.0" encoding="UTF-8"?><VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>%s</Status></VersioningConfiguration>' body = versioningBody % status result = reqs "PUT", rel_path, data=body, params={} return result end def get_bucket_versioning(bucket) #查看当前桶的版本控制信息,返回桶的状态("Enabled"或者"Suspended"或者"") rel_path = get_path "%s?versioning" % bucket result = reqs "GET", rel_path, "none", {} end def get_object_versions(bucket) #获取当前桶内的所有对象的所有版本信息 rel_path = get_path "%s?versions" % bucket result = reqs "GET", rel_path, "none", {} end def download_object_data(bucket, key) =begin 下载桶内对象的数据 参数: bucket: 桶名 key: 对象名 =end rel_path = get_path "%s/%s" % [bucket, key] result = reqs "GET", rel_path, "none", {} return result end def update_bucket_acl(bucket, header_params={}) =begin 修改桶的权限 参数: bucket: 桶名 header_params: 请求头参数, 是一个字典 {'x-amz-acl':test} test: 允许值 private:自己拥有全部权限,其他人没有任何权限 public-read:自己拥有全部权限,其他人拥有读权限 public-read-write:自己拥有全部权限,其他人拥有读写权限 authenticated-read:自己拥有全部权限,被授权的用户拥有读权限 =end rel_path = get_path "%s?acl" % bucket result = reqs "PUT", rel_path, nil, params=header_params return result end def update_object_acl(bucket, key, header_params={}) =begin 修改桶内对象的权限 参数: bucket: 桶名 key: 对象名 header_params: 请求头参数, 是一个字典 Hash['x-amz-acl'=>'public-read'] test: 允许值 private:自己拥有全部权限,其他人没有任何权限 public-read:自己拥有全部权限,其他人拥有读权限 public-read-write:自己拥有全部权限,其他人拥有读写权限 authenticated-read:自己拥有全部权限,被授权的用户拥有读权限 =end rel_path = get_path "%s/%s?acl" % [bucket, key] result = reqs "PUT", rel_path, nil, params=header_params end def update_versioning_object_acl(bucket, key, versionId, header_params={}) =begin 修改桶内版本管理对象的权限 参数: bucket: 桶名 key: 对象名 versionId: 对象版本号 header_params: 请求头参数, 是一个字典 Hash['x-amz-acl'=>'public-read'] test: 允许值 private:自己拥有全部权限,其他人没有任何权限 public-read:自己拥有全部权限,其他人拥有读权限 public-read-write:自己拥有全部权限,其他人拥有读写权限 authenticated-read:自己拥有全部权限,被授权的用户拥有读权限 =end rel_path = get_path "%s/%s?acl&versionId=%s" % [bucket, key, versionId] result = reqs "PUT", rel_path, nil, params=header_params return result end def storing_object_data(bucket, key, update_data, update_type, header_params={}) =begin 创建存储桶内对象 参数: bucket: 桶名 key: 对象名 update_data: 对象的内容(文件的路径/字符串) update_type: 对象内容类型 允许值 'file','string' =end rel_path = get_path "%s/%s" % [bucket, key] if update_type == "data" or update_type == "string" update_content = update_data content_length = update_data.length content_md5 = Digest::MD5.hexdigest(update_content) result = reqs "PUT", rel_path, data=update_content, params=header_params return result end if update_type == "file" result = upload_big_data(bucket, key, update_data, header_params) return result end end def upload_big_data_one(bucket, key, header_params) rel_path = get_path "%s/%s?uploads" % [bucket, key] xml = reqs "POST", rel_path, nil, header_params roots = REXML::Document.new(xml) upload_id = roots.root.elements["UploadId"].text return upload_id end def upload_big_data_two(bucket, key, update_data, part_number, upload_id, header_params) update_content = update_data rel_path = get_path "%s/%s?partNumber=%s&uploadId=%s" % [bucket, key, part_number, upload_id] return upload_big_data_put("PUT", rel_path, update_content, header_params) end def upload_big_data(bucket, key, update_data, header_params) uid = upload_big_data_one(bucket, key, header_params) rel_path = get_path "%s/%s?uploadId=%s" % [bucket, key, uid] size = File::size?(update_data) rock = 1024.0 * 1024 * 20 if !size return "" end if size > (1024.0 * 1024 * 1024) puts "file is bigger than 1G" return "file is bigger than 1G" end i = size / (1024.0 * 1024 * 20) #i = 1.5 content = "" x = 0 File.open(update_data, "r") do |f| while x < i chunk = f.read(rock) etag = upload_big_data_two(bucket, key, chunk, x+1, uid, header_params) content += "<Part><PartNumber>%s</PartNumber><ETag>%s</ETag></Part>" % [x+1, etag] x += 1 end end content = '<CompleteMultipartUpload>' + content + '</CompleteMultipartUpload>' result = reqs "POST", rel_path, data=content, params=header_params return result end end