text
stringlengths
10
2.61M
require_relative 'app_spec_helper' describe "Delete" do describe "Delete Valid ID" do id = "56e40252133859262d000021" delete "/venues/#{id}" response = last_response it "should respond with status 204" do expect(response.status).to eql(204) end it "should respond with duration in the header" do expect(response.header["x-duration"].to_s).to match(/(\d)$/) end it "should then be deleted" do get "/venues/#{id}" expect(last_response.body).to eql(not_found_with_id_error(id)) end end describe "Delete Invalid ID" do delete '/venues/someInvalidID' response = last_response it "should respond with status 404" do expect(response.status).to eql(404) end it "should return correct body error" do expect(response.body).to eql(not_found_with_id_error("someInvalidID")) end end end
class ApplicationController < ActionController::API include DeviseTokenAuth::Concerns::SetUserByToken rescue_from Pagy::OverflowError, with: :render_pagination_error include Pagy::Backend around_action :switch_locale before_action :configure_permitted_parameters, if: :devise_controller?, except: :callback before_action :check_user_confirmation_status, unless: :devise_controller? after_action { pagy_headers_merge(@pagy) if @pagy } protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :birth_date, :phone_number, :fcm_token]) end def render_pagination_error render json: {errors: []}, status: 200 end def switch_locale(&action) current_user.update_columns(locale: request.headers['locale']) if current_user && current_user.locale != request.headers['locale'] locale = request.headers['locale'] || I18n.default_locale I18n.with_locale(locale, &action) end def check_user_confirmation_status # if current_user && current_user.confirmed_at.nil? # render json: { error: { message: 'user not confirmed' } }, status: :forbidden # end end end
class CreateContracts < ActiveRecord::Migration[6.0] def change create_table :contracts do |t| t.string :place t.string :name t.string :document_id t.integer :age t.string :marital_status t.integer :phone t.string :email t.string :service_to_hire t.string :career t.string :academic_degree t.decimal :amount_pay, :precision => 8, :scale => 2 t.integer :fractional_payment t.string :way_to_pay t.string :type_of_service t.string :discover t.boolean :reader, default: true t.timestamps end end end
class CurrentUserSerializer < UserSerializer embed :ids, include: true attributes :email, :newUsername, :sfw_filter, :last_backup, :has_dropbox?, :has_facebook?, :confirmed?, :pro_expires_at, :import_status, :import_from, :import_error has_one :pro_membership_plan def newUsername object.name end end
module Asyncapi::Server class JobWorker include Sidekiq::Worker sidekiq_options retry: false MAX_RETRIES = 2 def perform(job_id, retries=0) job = Job.find(job_id) runner_class = job.class_name.constantize job_status = :success job_message = runner_class.call(job.params) rescue => e job_status = :error job_message = [e.message, e.backtrace].flatten.join("\n") raise e ensure if job job.update(status: job_status) report_job_status(job, job_message) else # For some reason "ActiveRecord::Base.after_transaction", # ":after_commit" and ":after_create" does not prevent # the ActiveRecord-Sidekiq race condition. In order to # prevent this just retry running JobWorker until it finds # the job by job_id. if retries <= MAX_RETRIES JobWorker.perform_async(job_id, retries+1) end end end private def report_job_status(job, job_message) JobStatusNotifierWorker.perform_async(job.id, job_message) end end end
class RemoveProjectConfirmationToProjects < ActiveRecord::Migration def change remove_column :projects, :project_confirmation, :boolean end end
class Offer < ActiveRecord::Base belongs_to :product has_one :counteroffer, dependent: :destroy end
require 'rails_helper' RSpec.describe Lesson, type: :model do it { is_expected.to validate_presence_of(:date_at) } it { is_expected.to validate_presence_of(:home_task) } it { is_expected.to validate_presence_of(:description) } it { is_expected.to allow_value('2021/04/21').for(:date_at)} end
#!/usr/bin/env ruby require 'optparse' require_relative 'lib/git_stat_tool_user' def get_user options = {} optparse = OptionParser.new do|opts| opts.on( '-h', '--help', 'Display this screen' ) do puts opts exit end options[:username] = false opts.on( '-u', '--username USERNAME', "GitHub username" ) do|f| options[:username] = f end options[:password] = false opts.on( '-p', '--password PASSWORD', "GitHub password" ) do|f| options[:password] = f end end optparse.parse! if options[:username] username = options[:username] else username = @tool_user.get_username end if options[:password] password = options[:password] else password = @tool_user.get_user_password end user = @tool_user.init_user(username, password) end ########### Tool Control ########### @tool_user = GitStatToolUser.new @tool_repo = GitStatToolRepo.new @user = get_user @repos = @tool_repo.get_repos(@user) @tool_repo.print_repos(@repos) @repos = @tool_repo.select_repo(@repos)
class AttachmentUploader < CarrierWave::Uploader::Base storage :qiniu def store_dir time = Time.now.strftime('%Y%m%d%H%M') "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}/#{time}" end def filename original_filename end # def default_url # # For Rails 3.1+ asset pipeline compatibility: # "http://#{self.qiniu_bucket_domain}/uploads/defaults/" + [version_name, "default_#{mounted_as}.jpg"].compact.join('_') # end end
class CreateEntries < ActiveRecord::Migration def change create_table :entries do |t| t.text :caption t.datetime :original_created_at t.string :source_name t.string :source_url t.string :title t.timestamps end end end
class AddColumnSpecialityToCostCenters < ActiveRecord::Migration def change add_column :cost_centers, :speciality, :string end end
require 'rails_helper' RSpec.describe Station, :type => :model do subject(:station) { create(:station) } it 'has the user' do expect(station.user).to be_a(User) end end
require 'active_collab/object' class ActiveCollab::Project < ActiveCollab::Object::Record include ActiveCollab::Object::Saveable has_routes({ :create => "/projects/add", :read => "/projects/:id", :update => "/projects/:id/edit", :index => "/projects" }) has_attributes :id, :name, :permalink, :verbose_type, :verbose_type_lowercase, :urls, :permissions, :created_on, :created_by_id, :updated_on, :updated_by_id, :state, :is_archived, :is_trashed, :completed_on, :completed_by_id, :is_completed, :avatar, :category_id, :label_id, :is_favorite, :custom_fields, :icon, :overview, :overview_formatted, :currency_code, :based_on, :status_verbose, :progress, :budget, :leader_id, :company_id def tasks if !@client.nil? @client.tasks(self.id) else [] end end def new_task ActiveCollab::Task.new(project_id: id) end end
require 'data_mapper' class DmPortfolio include DataMapper::Resource validates_presence_of :weights validates_uniqueness_of :weights_md5_hash property :id, Serial property :weights, Json property :weights_md5_hash, String, index: true belongs_to :dm_efficient_frontier, required: false ## CLASS ## def self.with_weights(weights_hash) return [] if weights_hash.empty? first( weights_md5_hash: md5_hash(normalize_weights(weights_hash)) ) end ## INSTANCE ## def weights=(hash) normalized = self.class.normalize_weights(hash) self.weights_md5_hash = self.class.md5_hash(normalized) super(normalized) end private def self.normalize_weights(hash) Hash[hash.sort].inject({}) {|h, (k,v)| h[k.upcase] = v.to_f; h } end def self.md5_hash(hash) Digest::MD5.hexdigest(hash.to_json) end end # DmPortfolio
class Cell attr_accessor :row, :column, :content, :visited def initialize(row, column) @row = row @column = column @content = "#" @visited = false end def visited? @visited end def end? return true if @content == "E" return false end def open @content = " " end def find_neighbor(grid) neighbors = Array.new top = grid[@row - 1][@column] right = grid[@row][@column + 1] bottom = grid[@row + 1][@column] left = grid[@row][@column - 1] if !top.nil? && !top.visited neighbors << top end if !right.nil? && !right.visited neighbors << right end if !bottom.nil? && !bottom.visited neighbors << bottom end if !left.nil? && !left.visited neighbors << left end if neighbors.length > 0 random = Random.rand(0..neighbors.length-1) n = neighbors[random] return n else return nil end end end class MazeGenerator def initialize(size) @rows = size @columns = size @cell_content = "#" @grid = Array.new @current = nil end def setup for row in 0..@rows + (@rows) submap = Array.new for column in 0..@columns + (@columns) submap << Cell.new(row, column) end @grid << submap end @start = @grid[1][0] @end = @grid[ @grid.length - 2][ @grid.length - 1] # set start and end @start.content = "S" @end.content = "E" end def generate setup @current = @start # while !@current.end? # walk # sleep(0.03) # draw # end end def walk @current.visited = true @current.open next_cell = @current.find_neighbor(@grid) if !next_cell.nil? next_cell.visited = true @current = next_cell end end def draw @grid.each do |line| line.each do |cell| print cell.content end puts '' end puts '' end end g = MazeGenerator.new(5) g.generate g.draw
class BootstrapThumbnailCollectionRenderer < ResourceRenderer::CollectionRenderer::Base def render(&block) helper.capture do helper.content_tag(:div, class: 'row') do render_collection(&block) end end end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Pitzi::V1::BaseAPI, type: :api do describe 'Configurations' do it 'has json format' do expect(described_class.format).to eq :json end it 'has v1 version' do expect(described_class.version).to eq :v1 end it 'mounts Pitzi::V1::OrdersAPI app' do expect(described_class.routes.to_a).to include(*Pitzi::V1::OrdersAPI.routes.to_a) end it 'mounts Pitzi::V1::UsersAPI app' do expect(described_class.routes.to_a).to include(*Pitzi::V1::UsersAPI.routes.to_a) end end end
require 'rails_helper' RSpec.describe Product, type: :model do before(:each) do @category = Category.new(name: 'furniture') @product = Product.new(name: 'big comfy couch', price_cents: 1000000, quantity: 2, category: @category) end describe 'Validations' do it 'should save a valid product' do @product.save end it 'should not save without valid name' do @product.name = nil expect(@product.valid?).to be false end it 'should not save without valid price' do @product.price_cents = nil expect(@product.valid?).to be false end it 'should not save without valid quantity' do @product.quantity = nil expect(@product.valid?).to be false end it 'should not save without valid category' do @product.category = nil expect(@product.valid?).to be false end end end
class ModifyRefernces < ActiveRecord::Migration[5.2] def self.up remove_reference :parking_slots, :floor, foreign_key: true add_reference :parking_slots, :block, foreign_key: true end def self.down add_reference :parking_slots, :floor, foreign_key: true remove_reference :parking_slots, :block, foreign_key: true end end
class RemoveNameFromPageAsset < ActiveRecord::Migration[5.0] def change remove_column :page_assets, :name, :string end end
#!/usr/bin/env ruby # RemoteObjectManager # # Copyright 2011 Voltaic # # 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. #!!! ChannelMultiplexer.flush_stream needs to heed max_transfer <<__SYNTAX_COLOR__ # At least in Aquamacs, this makes the next 'here' document get syntax-colored.... __SYNTAX_COLOR__ ( <<'__END_REMOTE_OBJECT_MANAGER_SOURCE__' require 'thread' require 'monitor' require 'stringio' module RemoteObjectManager CM_TRACE = false class ChannelMultiplexer DEFAULT_LATENCY = 0.5 LATENCY_LIMITS = [0.05, 10.0].freeze DEFAULT_BUFFER_SIZE = 256 BUFFER_SIZE_LIMITS = [256, 16384].freeze STANDARD_RAW_CHANNELS = [:underlying].freeze STANDARD_DATA_CHANNELS = [:value, :exception].freeze ENDPOINT_SYMBOLS = [:r, :w].freeze ALLOCATED_CHANNEL_PREFIX = 'channel_' # for channels allocated by add_channel with ch == nil def initialize(the_underlying, options={}) # options: :protocol_class, :latency, :buffer_size begin opt_protocol_class = options.delete(:protocol_class) || DefaultProtocol opt_latency = [ [ LATENCY_LIMITS.first, (options.delete(:latency).to_f || DEFAULT_LATENCY) ].max, LATENCY_LIMITS.last ].min opt_buffer_size = [ [ BUFFER_SIZE_LIMITS.first, (options.delete(:buffer_size).to_i || DEFAULT_BUFFER_SIZE) ].max, BUFFER_SIZE_LIMITS.last ].min @underlying = the_underlying @underlying.flush @underlying_endpts = make_channel_endpoints(false) # we need these now, but add_channel requires the protocol object; add_channel is special-cased for :underlying underlying_redirection = Redirection.new(@underlying, @underlying_endpts[:w]) (@redirections ||= []) << underlying_redirection @protocol = opt_protocol_class.new(@underlying, opt_latency, opt_buffer_size) underlying_redirection.redirect @channel_pipes = {} # non-nil indicates open STANDARD_RAW_CHANNELS.each{|ch| add_channel(ch, true)} STANDARD_DATA_CHANNELS.each{|ch| add_channel(ch, false)} # we were single-threaded until: @bg = Thread.new(self){|cm| cm.thread_proc} rescue => e close(true) rescue nil raise e end end def closed? !@channel_pipes end def add_channel(ch=nil, raw=false, existing_stream=nil) # ch: channel symbol; nil => allocate new symbol # raw: non-false value => string representation of data is put on multiplexer_stream, otherwise data is marshaled into multiplexer_stream # existing_stream: stream to redirect to the multiplexer; nil => no redirection # returns: [channel_symbol, multiplexer_stream] @protocol.synchronize do raise StandardError.new("add_channel(ch=#{ch.inspect}, raw=#{raw.inspect}, existing_stream=#{existing_stream.inspect}): ChannelMultiplexer object is closed") if closed? raise StandardError.new("add_channel(ch=#{ch.inspect}, raw=#{raw.inspect}, existing_stream=#{existing_stream.inspect}): existing_stream specified for :underlying channel") if ch == :underlying && !existing_stream.nil? raise StandardError.new("add_channel(ch=#{ch.inspect}, raw=#{raw.inspect}, existing_stream=#{existing_stream.inspect}): channel must be a symbol") unless ch.is_a?(Symbol) raise StandardError.new("add_channel(ch=#{ch.inspect}, raw=#{raw.inspect}, existing_stream=#{existing_stream.inspect}): existing channel specified") if @channel_pipes.has_key?(ch) ch = allocate_channel_id if ch.nil? endpts = (ch == :underlying) ? @underlying_endpts : make_channel_endpoints(raw) # needed @underlying_endpts early in the bootstrap process if existing_stream redirection = Redirection.new(existing_stream, endpts[:w]) redirection.redirect (@redirections ||= []) << redirection end @channel_pipes[ch] = endpts @protocol.notify_add_channel(ch, raw) [ch, endpts[:w]] end end def remove_channel(ch) @protocol.synchronize do raise StandardError.new("closed: remove_channel(#{ch.inspect})") if closed? raise StandardError.new("remove_channel(ch=#{ch.inspect}): standard channel specified") if STANDARD_CHANNELS.include?(ch) raise StandardError.new("remove_channel(ch=#{ch.inspect}): undefined channel specified") unless @channel_pipes.has_key?(ch) raise StandardError.new("remove_channel(ch=#{ch.inspect}): underlying channel specified") if ch == :underlying flush # desynchronize here? We've used Monitor instead of Mutex, so we don't have to.... @channel_pipes.delete(ch).channel_pipes.each{|epsym, ep| ep.close rescue nil} @protocol.notify_remove_channel(ch) end nil end def send(ch, data) (puts ">>> send(ch=#{ch.inspect}, data)"; $stdout.flush) if CM_TRACE @protocol.synchronize do cpipe = @channel_pipes[ch][:w] @protocol.write_to_channel_pipe(cpipe, ch, data) cpipe.flush end nil end def send_value(v) send(:value, v) end def send_exception(e) send(:exception, e) end def context(*args, &block) raise StandardError.new("closed: context") if closed? raise StandardError.new("no block specified: context") if block.nil? begin (puts "<<< calling block for send_value"; $stdout.flush) if CM_TRACE value = block.call(*args) (puts "<<< send_value(value=#{value.inspect})"; $stdout.flush) if CM_TRACE send_value(value) (puts "<<< returned from send_value(value=#{value.inspect})"; $stdout.flush) if CM_TRACE rescue Exception => e # is Exception too broad? (puts "<<< send_exception(e=#{e.inspect})"; $stdout.flush) if CM_TRACE send_exception(e) (puts "<<< returned from send_exception(e=#{e.inspect})"; $stdout.flush) if CM_TRACE end nil end def flush(force=false) raise StandardError.new("closed") if closed? self.class.flush_ignoring_closed(@channel_pipes, @protocol, force) end def close(force=false) return nil if closed? begin # Note: we assume that @protocol is not nil if we ever get here @protocol.synchronize do # First, set to closed state cpipes = @channel_pipes @channel_pipes = nil # closed? will return true now # Now close the write endpoints so that no new data will arrive from the channels cpipes.each{|ch, eps| eps[:w].close rescue nil} if cpipes # Then flush all the channel pipes into the protocol self.class.flush_ignoring_closed(cpipes, @protocol, force) # Now close the read endpoints; the channel pipe ares done with cpipes.each{|ch, eps| eps[:r].close rescue nil} cpipes = nil # done with this now # Now flush the protocol to the :underlying stream @protocol.flush end if @bg # because @channel_pipes is nil, the thread will exit even if @protocol is nil (which would be strange, but anyway...) @bg.join @bg = nil end @protocol.synchronize do @protocol.close @protocol = nil end if @protocol rescue => e raise e unless force ensure @channel_pipes = nil @redirections.reverse.each{|rc| rc.restore} rescue nil # restore last-to-first @redirections = nil # don't close the :underlying pipe endpoints until after we've replaced the orginal stream so the parent process does not get an EOF if @underlying_endpts @underlying_endpts.each{|epsym, ep| ep.close rescue nil} @underlying_endpts = nil end end nil end protected class Redirection attr_reader :old_io, :new_io, :state def initialize(the_old_io, the_new_io) @old_io = the_old_io @orig_io = @old_io.dup @new_io = the_new_io @state = :init end def redirect @old_io.flush @old_io.reopen(@new_io) @state = :redirected end def restore if @state == :redirected @old_io.flush @old_io.reopen(@orig_io) end @state = :done end end def self.flush_ignoring_closed(cpipes, protocol, force) protocol.synchronize do begin cpipes.each{|ch, eps| eps[:w].flush unless eps[:w].closed?} # Now, flush each of the pipes to the underlying stream. # However, do so in a round-robin fashion, transmitting # buffer_size-sized buffers. This will make all streams # get serviced promptly even if some streams are sending # a lot of data. loop do finished = cpipes.collect do |ch, eps| n = 0 n = ChannelMultiplexer.flush_stream(eps[:r], protocol.buffer_size, protocol.buffer_size){|data| protocol.send_data(ch, data)} unless eps[:r].closed? n <= 0 end break if finished.all? end protocol.flush rescue => e raise e unless force end end nil end def make_channel_endpoints(raw=false) Hash[ENDPOINT_SYMBOLS.zip(IO.pipe)].freeze end def allocate_channel_id @protocol.synchronize do max_n = @channel_pipes.keys.collect{|k| ks = k.to_s; (ks =~ /^#{ALLOCATED_CHANNEL_PREFIX}/).nil? ? nil : ks[ALLOCATED_CHANNEL_PREFIX.length, ks.length-ALLOCATED_CHANNEL_PREFIX.length]}.compact.select{|ks| ki = (ks.to_i rescue 0); ki.to_s == ks && ki >= 0}.collect{|ks| ks.to_i}.max next_n = max_n ? max_n+1 : 0 ("#{ALLOCATED_CHANNEL_PREFIX}#{max_n}").to_sym end end def thread_proc loop do break if closed? start = Time.now flush rescue nil unless closed? #!!! handle error? break if closed? timeout = @protocol.latency - (Time.now - start) sleep(timeout) unless closed? || timeout <= 0.0 end end public def self.flush_stream(stream, buffer_size=DEFAULT_BUFFER_SIZE, max_transfer=nil, &block) # returns number of bytes transferred, or -1 if EOF #!!! use max_transfer raise StandardError.new("flush_stream: no block specified") if block.nil? n = 0 calling_block = false begin stream = StringIO.new(stream) if stream.is_a?(String) if stream.is_a?(StringIO) # convert stream to a String loop do data = stream.read(buffer_size) data_size = data ? data.size : 0 return -1 if data_size <= 0 && n <= 0 # indicate: EOF break if data_size <= 0 n += data_size (calling_block = true; block.call(data); calling_block = false) end else loop do read_eps, ignored_write_eps, ignored_error_eps = IO.select([stream], nil, nil, 0.0) # note: StringIO objects don't work with select break unless read_eps read_eps.each do |ep| unless ep.closed? data = stream.read_nonblock(buffer_size) data_size = data ? data.length : 0 break if data_size <= 0 n += data_size (calling_block = true; block.call(data); calling_block = false) end end end end rescue EOFError => e raise if calling_block # pass exception on; didn't want to keep establishing exception context, so used this flag return -1 unless n > 0 # indicate: EOF end n end def self.write_to_stream(stream, data) n = 0 while data.length-n > 0 begin n += stream.write_nonblock(n <= 0 ? data : data[n, data.length-n]) rescue Errno::EINTR, Errno::EAGAIN#!!!, IO::WaitWritable IO.select(nil, [stream]) #!!! timeout? retry end end end FORKEXEC_ACTIONS = { :stdin => { :init=>lambda{|state| state[:pipe] = IO.pipe}, :parent=>lambda{|state| state[:pipe][0].close rescue nil}, :child=>lambda{|state| $stdin.reopen(state[:pipe][0]); state[:pipe][1].close rescue nil}, :endpt=>lambda{|state| state[:pipe][1]} }, :stdout => { :init=>lambda{|state| state[:pipe] = IO.pipe}, :parent=>lambda{|state| state[:pipe][1].close rescue nil}, :child=>lambda{|state| $stdout.reopen(state[:pipe][1]); state[:pipe][0].close rescue nil}, :endpt=>lambda{|state| state[:pipe][0]} }, :stderr => { :init=>lambda{|state| state[:pipe] = IO.pipe}, :parent=>lambda{|state| state[:pipe][1].close rescue nil}, :child=>lambda{|state| $stderr.reopen(state[:pipe][1]); state[:pipe][0].close rescue nil}, :endpt=>lambda{|state| state[:pipe][0]} }, } def self.forkexec_with_redirects(cmd, redirects=nil) redirects = (redirects ||= []).uniq unknown = redirects-FORKEXEC_ACTIONS.keys raise StandardError.new('unknown redirect symbols: #{unknown.inspect}') if unknown.count > 0 states = {} redirects.each{|r| FORKEXEC_ACTIONS[r][:init].call(states[r] ||= {})} pid = fork do redirects.each{|r| FORKEXEC_ACTIONS[r][:child].call(states[r])} exec(cmd) end redirects.each{|r| FORKEXEC_ACTIONS[r][:parent].call(states[r])} [pid, Hash[redirects.collect{|r| [r, FORKEXEC_ACTIONS[r][:endpt].call(states[r])]}]] end class BaseProtocol RESERVED_PROTOCOL_CHANNEL = nil # the channel on which protocol notifications will be sent; nil is a good value because the client looks for an empty channel id for this channel attr_reader :latency, :buffer_size def initialize(the_marshaler, the_stream, the_latency, the_buffer_size) @lock = Monitor.new # get this while we're still single-threaded; lazy creation in synchronize() would leave a race condition; note: Monitor allows the same thread to re-enter @marshaler = the_marshaler @stream = the_stream.dup @latency = the_latency @buffer_size = the_buffer_size @buffer = StringIO.new @raw_channels = [] end def synchronize(*args, &protected_block) @lock.synchronize(*args, &protected_block) end def raw_channel?(ch) @raw_channels.include?(ch) end def send_start # nothing... end def notify_add_channel(ch, raw) @raw_channels << ch if raw end def notify_remove_channel(ch) @raw_channels.delete(ch) end def send_data(ch, data) (puts "<<< send_data(ch=#{ch.inspect}, data=#{data.inspect})"; $stdout.flush) if CM_TRACE send_start unless @start_sent # We packetize data from raw streams now. # It doesn't really matter how we divide the raw stream data into packets, and, # besides, we don't necessarily control what data is placed on the raw channel pipes. # However, data streams must be packetized as soon as the data is sent to the channel pipe # so that the marshaled data is contiguous in the protocol stream. # Special case: data for the RESERVED_PROTOCOL_CHANNEL is packetized because that channel # has no channel pipe. See send_notification. data = self.class.packetize(ch, data) if raw_channel?(ch) || ch == RESERVED_PROTOCOL_CHANNEL @buffer << data (puts "<<< send_data: @buffer.pos=#{@buffer.pos.inspect} data=#{data.inspect}"; $stdout.flush) if CM_TRACE flush if @buffer.pos >= @buffer_size end def send_end # nothing... end def flush if @buffer.pos > 0 ChannelMultiplexer.write_to_stream(@stream, @buffer.string[0, @buffer.pos]) @buffer.pos = 0 end @stream.flush end def close flush @raw_channels = nil end def write_to_channel_pipe(cpipe, ch, data) # implements the bulk of ChannelMultiplexer#send (puts "<<< write_to_channel_pipe(cpipe=#{cpipe.inspect}, ch=#{ch.inspect}, data=#{data.inspect})"; $stdout.flush) if CM_TRACE data = raw_channel?(ch) ? data.to_s : marshaler_dump(data) return nil if data.nil? # exception in marshaler_dump # We packetize data from non-raw (i.e., data) streams now so that # the marshaled data is contiguous in the protocol stream. # Raw streams are packetized in send_data. data = self.class.packetize(ch, data) unless raw_channel?(ch) ChannelMultiplexer.write_to_stream(cpipe, data) (puts "<<< write_to_channel_pipe(cpipe=#{cpipe.inspect}, ch=#{ch.inspect}, data=#{data.inspect})"; $stdout.flush) if CM_TRACE nil end protected # marshaler_dump should be overridden to provide a means of recording marshal errors, if any are possible. # if such an error occurs, marshaler_dump must return nil. def marshaler_dump(obj) @marshaler.dump(obj) end public class BaseConnection DEFAULT_BOOTSTRAP_REMOTE_HERE_DOC_TOKEN = '__END_REMOTE_OBJECT_MANAGER_SOURCE__' DEFAULT_BOOTSTRAP_WAIT_TIMEOUT = 0.1 def process # returns false iff there is nothing left to process raise RuntimeError.new(':process must be overrridden') end def remote_bootstrap(remote_in, remote_object_manager_source, options={}) # options: :remote_here_doc_token, :code, :return_immediately, :wait_timeout remote_here_doc_token = options.delete(:remote_here_doc_token) || DEFAULT_BOOTSTRAP_REMOTE_HERE_DOC_TOKEN code = options.delete(:code) return_immediately = options.delete(:return_immediately) wait_timeout = options.delete(:wait_timeout) || DEFAULT_BOOTSTRAP_WAIT_TIMEOUT ChannelMultiplexer.write_to_stream(remote_in, "\n( <<'#{remote_here_doc_token}'\n") ChannelMultiplexer.write_to_stream(remote_in, remote_object_manager_source) # Note: this is the variable that contains this definition... ChannelMultiplexer.write_to_stream(remote_in, "\n#{remote_here_doc_token}\n") ChannelMultiplexer.write_to_stream(remote_in, ").tap do |remote_object_manager_source|\n") ChannelMultiplexer.write_to_stream(remote_in, " eval(remote_object_manager_source)\n") ChannelMultiplexer.write_to_stream(remote_in, " RemoteObjectManager.const_set(:SOURCE, remote_object_manager_source)\n") ChannelMultiplexer.write_to_stream(remote_in, "end\n") if code && code.is_a?(String) ChannelMultiplexer.write_to_stream(remote_in, code) code = nil end return if return_immediately if code remote_in.flush else remote_in.close rescue nil remote_in = nil end while process do if remote_in if code && ChannelMultiplexer.flush_stream(code){|data| ChannelMultiplexer.write_to_stream(remote_in, data)} >= 0 # otherwise, code EOF remote_in.flush else remote_in.close rescue nil remote_in = nil end end sleep wait_timeout end nil end DEFAULT_UNDERLYING_ENDPT = :stderr def self.remote_process_bootstrap(command, remote_object_manager_source, code=nil, options={}) #!!! NEVER RETURNS IF code=nil # options: :underlying_endpt, :remote_here_doc_token (for remote_bootstrap), :return_immediately (for remote_bootstrap), :wait_timeout (for remote_bootstrap) underlying_endpt = options.delete(:underlying_endpt) || DEFAULT_UNDERLYING_ENDPT connection_class = self pid = endpts = nil conn = nil begin (puts "remote_process_bootstrap: forkexec: command=|#{command}|"; $stdout.flush) if CM_TRACE pid, endpts = ChannelMultiplexer.forkexec_with_redirects(command, [:stdin, underlying_endpt]) conn = connection_class.new(endpts[underlying_endpt]) options = options.merge(:code=>code) if code conn.remote_bootstrap(endpts[:stdin], remote_object_manager_source, options) Process.wait(pid) if pid return conn.outputs ensure endpts.each{|r, ep| ep.close rescue nil if ep} if endpts end end end end class DefaultProtocol < BaseProtocol MAJOR_VERSION = 0 MINOR_VERSION = 1 MARSHALER_CLASS = Marshal NOTIFICATION_ADD_CHANNEL = :add NOTIFICATION_REMOVE_CHANNEL = :remove NOTIFICATION_END = :end NOTIFICATION_INTERNAL_ERROR = :internal_error SPECIFIER_RAW = :raw SPECIFIER_DATA = :data # PROTOCOL STREAM STRUCTURE: # <PROTOCOL_STREAM> ::= <PROTOCOL_HEADER> <NON_END_CHANNEL_MESSAGE>* <END_CHANNEL_MESSAGE> # <NON_END_CHANNEL_MESSAGE> ::= <ADD_CHANNEL_MESSAGE> | # <REMOVE_CHANNEL_MESSAGE> | # <INTERNAL_ERROR_MESSAGE> | # <CHANNEL_DATA_MESSAGE> | # <CHANNEL_RAW_MESSAGE> # <ADD_CHANNEL_MESSAGE> ::= ch.to_s "\0" timestamp.to_s "\0" data_length.to_s "\0" [:add, [ch, <CHANNEL_FORMAT_SPECIFIER>]] # <REMOVE_CHANNEL_MESSAGE> ::= ch.to_s "\0" timestamp.to_s "\0" data_length.to_s "\0" [:remove, ch] # <INTERNAL_ERROR_MESSAGE> ::= ch.to_s "\0" timestamp.to_s "\0" data_length.to_s "\0" [:internal_error, [location_symbol, internal_error_exception]] # <END_CHANNEL_MESSAGE> ::= ch.to_s "\0" timestamp.to_s "\0" data_length.to_s "\0" [:end, nil] # <CHANNEL_DATA_MESSAGE> ::= ch.to_s "\0" timestamp.to_s "\0" marshaled_data_length.to_s "\0" marshaled_data # <CHANNEL_RAW_MESSAGE> ::= ch.to_s "\0" timestamp.to_s "\0" raw_data_length.to_s "\0" raw_data # <CHANNEL_FORMAT_SPECIFIER> ::= 'raw' | 'data' class << self def monicker @@monicker ||= "#{self.name}({:version=>#{MAJOR_VERSION}.#{MINOR_VERSION}, :marshaler_class=>#{MARSHALER_CLASS.name}, :marshaler_version=>#{MARSHALER_CLASS::MAJOR_VERSION}.#{MARSHALER_CLASS::MINOR_VERSION}})" end def protocol_header @@protocol_header ||= "\n#{monicker} BEGIN\n" end end def initialize(the_stream, the_latency, the_buffer_size) super(MARSHALER_CLASS, the_stream, the_latency, the_buffer_size) @start_sent = false @end_sent = false end def send_start @buffer << self.class.protocol_header @start_sent = true super end def notify_add_channel(ch, raw) send_notification(NOTIFICATION_ADD_CHANNEL, [ch, (raw ? SPECIFIER_RAW : SPECIFIER_DATA)]) super(ch, raw) end def notify_remove_channel(ch) send_notification(NOTIFICATION_REMOVE_CHANNEL, ch) super(ch) end def send_end send_start unless @start_sent send_notification(NOTIFICATION_END) @end_sent = true super end def close send_end unless @end_sent || !@start_sent super end protected def marshaler_dump(obj) super(obj) rescue => e send_start unless @start_sent send_notification(NOTIFICATION_INTERNAL_ERROR, [:marshaler_dump, e]) return nil # indicate: exception thrown end def send_notification(notification, notification_data=nil) # Note that we short-circuit the sending of the notification by sending directly # to the prptocol stream and bypassing the channel pipes. This is because # we do not allocate a pipe for the RESERVED_PROTOCOL_CHANNEL. send_data is # special-cased accordingly. data = marshaler_dump([notification, notification_data]) send_data(RESERVED_PROTOCOL_CHANNEL, data) unless data.nil? # data.nil? ==> exception in marshaler_dump end def self.packetize(ch, data) data ||= '' raise StandardError.new('data must be String or nil') unless data.is_a?(String) # note that symbols cannot contain "\0" # note that BaseProtocol::RESERVED_PROTOCOL_CHANNEL == nil so that channel name will be an empty string ( ch.to_s + "\0" + Time.now.utc.to_f.to_s + "\0" + data.length.to_s + "\0" + data ) end public class Connection < BaseProtocol::BaseConnection SERVER_PROTOCOL_CLASS = DefaultProtocol attr_reader :outputs def initialize(the_protocol_stream) @protocol_stream = the_protocol_stream.dup @outputs = { BaseProtocol::RESERVED_PROTOCOL_CHANNEL=>{} } @active_channels = [] @raw_channels = [] @buffer = StringIO.new @state = :get_header @channel_id = nil @data_size = nil @protocol_ended = false end def process # returns false iff there is nothing left to process return false if @protocol_ended @protocol_header ||= SERVER_PROTOCOL_CLASS.protocol_header loop do return false if @protocol_ended return true if IO.select([@protocol_stream], nil, nil, 0.0).nil? case @state when :get_header: @buffer << @protocol_stream.read(@protocol_header.length-@buffer.pos) loop do # skip garbage preceding header break if @buffer.pos <= 0 cmplen = [@buffer.pos, @protocol_header.length].min break if @buffer.string[0, cmplen] == @protocol_header[0, cmplen] # Delete up to the next occurrence of the first character of the protocol header, # or the whole string if there is no such occurrence. @buffer is not empty # because of prior conditions, so progress in the loop will be made. marker = @buffer.string.index(@protocol_header[0], (@buffer.string[0] == @protocol_header[0] ? 1 : 0)) @buffer.string = marker && marker < @buffer.length ? @buffer.string[marker, @buffer.length-marker] : '' @buffer.pos = @buffer.length end if @buffer.pos >= @protocol_header.length raise if @buffer.pos > @protocol_header.length header = @buffer.string[0, @protocol_header.length] raise StandardError.new("bad protocol header") if header != @protocol_header #!!! CHECK VERSION, ETC @buffer.pos = 0 @state = :get_channel_id end when :get_channel_id: c = @protocol_stream.getc raise EOFError.new if c.nil? if c != 0 @buffer.putc(c) else if @buffer.pos <= 0 @channel_id = BaseProtocol::RESERVED_PROTOCOL_CHANNEL else channel_id_str = @buffer.string[0, @buffer.pos] @channel_id = channel_id_str.to_sym rescue nil raise StandardError.new("bad channel id") if @channel_id.to_s != channel_id_str end @buffer.pos = 0 @state = :get_timestamp end when :get_timestamp: c = @protocol_stream.getc raise EOFError.new if c.nil? if c != 0 @buffer.putc(c) else timestamp_str = @buffer.string[0, @buffer.pos] @timestamp = timestamp_str.to_f rescue nil raise StandardError.new("bad timestamp") if @timestamp.to_s != timestamp_str @buffer.pos = 0 @state = :get_data_size end when :get_data_size: c = @protocol_stream.getc raise EOFError.new if c.nil? if c != 0 @buffer.putc(c) else data_size_str = @buffer.string[0, @buffer.pos] @data_size = data_size_str.to_i rescue nil raise StandardError.new("bad data size") if @data_size.to_s != data_size_str @buffer.pos = 0 @state = :get_data end when :get_data: @buffer << @protocol_stream.read(@data_size-@buffer.pos) if @data_size > 0 if @buffer.pos == @data_size data = @buffer.string[0, @buffer.pos] data_ok = false begin #!!! dangerous: data = SERVER_PROTOCOL_CLASS::MARSHALER_CLASS.load(data) unless @raw_channels.include?(@channel_id) data_ok = true rescue => load_error # put a :marshaler_load :internal_error into the BaseProtocol::RESERVED_PROTOCOL_CHANNEL (@outputs[BaseProtocol::RESERVED_PROTOCOL_CHANNEL][@timestamp] ||= []) << [:internal_error, [:marshaler_load, load_error]] end if data_ok # otherwise, we put an [:internal_error, [:marshaler_load, load_error]] entry into BaseProtocol::RESERVED_PROTOCOL_CHANNEL if @channel_id == BaseProtocol::RESERVED_PROTOCOL_CHANNEL handle_notification(@channel_id, data) else raise StandardError.new("unknown channel #{@channel_id.inspect}") unless @outputs.has_key?(@channel_id) end (@outputs[@channel_id][@timestamp] ||= []) << data (puts ">>> @outputs[#{@channel_id.inspect}][#{@timestamp.inspect}] << #{data.inspect}"; $stdout.flush) if CM_TRACE end @buffer.pos = 0 @state = :get_channel_id end else raise RuntimeError.new("unexpected state encountered: #{@state.inspect}", @state) end end !@protocol_ended end protected def handle_notification(ch, data) raise StandardError.new("bad data for add channel notification") unless data && data.is_a?(Array) && data.count == 2 notification, notification_data = data case notification when SERVER_PROTOCOL_CLASS::NOTIFICATION_ADD_CHANNEL: raise StandardError.new("bad notification_data for add channel notification") unless notification_data && notification_data.is_a?(Array) && notification_data.count == 2 ch, raw_spec = notification_data raise StandardError.new("bad channel specifier for add channel notification #{ch.inspect}") unless ch && ch.is_a?(Symbol) raise StandardError.new("bad raw specifier for add channel notification #{raw_spec.inspect}") unless raw_spec && [SERVER_PROTOCOL_CLASS::SPECIFIER_RAW, SERVER_PROTOCOL_CLASS::SPECIFIER_DATA].include?(raw_spec) raise StandardError.new("channel added when already present: #{ch.inspect}; active_channels=#{@active_channels.inspect}") if @active_channels.include?(ch) @active_channels << ch @raw_channels << ch if raw_spec == SERVER_PROTOCOL_CLASS::SPECIFIER_RAW @outputs[ch] ||= {} when SERVER_PROTOCOL_CLASS::NOTIFICATION_REMOVE_CHANNEL: ch = notification_data raise StandardError.new("bad channel specifier for add channel notification: #{ch.inspect}") unless ch && ch.is_a?(Symbol) raise StandardError.new("channel removed when not present: #{ch.inspect}") unless @active_channels.include?(ch) @active_channels.delete(ch) @raw_channels.delete(ch) when SERVER_PROTOCOL_CLASS::NOTIFICATION_INTERNAL_ERROR: location_symbol, internal_error_exception = notification_data # nothing to do... when SERVER_PROTOCOL_CLASS::NOTIFICATION_END: @protocol_ended = true else raise StandardError.new("unknown notification received", data) end end end end end def self.remote_process_bootstrap(command, remote_object_manager_source, code=nil, options={}) #!!! NEVER RETURNS IF code=nil # options: :underlying_endpt (for ChannelMultiplexer::BaseProtocol::remote_process_bootstrap), :remote_here_doc_token (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :return_immediately (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :wait_timeout (for ChannelMultiplexer::BaseProtocol::remote_bootstrap) ChannelMultiplexer::DefaultProtocol::Connection.remote_process_bootstrap(command, remote_object_manager_source, code, options) end # remote_process relies on the value of RemoteObjectManager::SOURCE which is # the source code for this module. It is evaled into this module after the # source is evaled, closing the definitional loop (through process, I might add....) DEFAULT_RAILS_STARTUP_CODE = 'lambda{|rails_root, rails_env| ENV["RAILS_ENV"] = rails_env if rails_env; Dir.chdir(rails_root); require rails_root+"/config/boot"; require rails_root+"/config/environment"}' DEFAULT_RAILS_ROOT = '/u/app/current' def self.start_rails(rails_root=nil, options={}) # options: :rails_env, :rails_startup_code rails_root ||= DEFAULT_RAILS_ROOT rails_env = options.delete(:rails_env) || ENV['RAILS_ENV'] rails_startup_code = options.delete(:rails_startup_code) || DEFAULT_RAILS_STARTUP_CODE rails_startup = "#{rails_startup_code}.call(#{rails_root.inspect}, #{rails_env.inspect})" eval(rails_startup) end def self.remote_process(command, code=nil, options={}) # options: :load_rails, :rails_root, :rails_env, :rails_startup_code, :underlying_endpt (for ChannelMultiplexer::BaseProtocol::remote_process_bootstrap), :remote_here_doc_token (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :return_immediately (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :wait_timeout (for ChannelMultiplexer::BaseProtocol::remote_bootstrap) load_rails = options.delete(:load_rails) rails_root = options.delete(:rails_root) || DEFAULT_RAILS_ROOT rails_env = options.delete(:rails_env) || ENV['RAILS_ENV'] rails_startup_code = options.delete(:rails_startup_code) || DEFAULT_RAILS_STARTUP_CODE rails_startup = load_rails ? "#{rails_startup_code}.call(#{rails_root.inspect}, #{rails_env.inspect})\n" : '' prefix = <<-'END_CODE_PREFIX' cm = nil begin cm = RemoteObjectManager::ChannelMultiplexer.new($stderr) cm.add_channel(:stdout, true, $stdout) cm.context do END_CODE_PREFIX suffix = <<-'END_CODE_SUFFIX' end ensure cm.close if cm end END_CODE_SUFFIX source = code || '' (source = ""; ChannelMultiplexer.flush_stream(code){|data| source += data}) if code.is_a?(IO) remote_process_bootstrap(command, RemoteObjectManager::SOURCE, rails_startup+prefix+source+suffix, options.merge(:underlying_endpt=>:stderr)) end class InternalError < StandardError; end class RemoteError < StandardError; end def self.process_eval(command, code=nil, options={}) # options: :channel_value_acceptors, :load_rails (for remote_process), :rails_root (for remote_process), :rails_env (for remote_process), :rails_startup_code (for remote_process), :remote_here_doc_token (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :return_immediately (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :wait_timeout (for ChannelMultiplexer::BaseProtocol::remote_bootstrap) # channel_value_acceptors: if nil, then the default_channel_value_acceptors are used. # Otherwise, channel_value_acceptors must be a hash of channels to procs that accept # data for that channel as data is replayed timestamp-wise. If any so-mapped channel # maps to nil, then the default implementation from default_channel_value_acceptors # is used. After defaults substitution, any nil-mapped channels are eliminated. result = nil default_value_acceptor_channels = [ChannelMultiplexer::BaseProtocol::RESERVED_PROTOCOL_CHANNEL, :value, :exception] default_channel_value_acceptors = { ChannelMultiplexer::BaseProtocol::RESERVED_PROTOCOL_CHANNEL => lambda{|ts, (notification, notification_data)| raise InternalError, [notification, notification_data] if notification == :internal_error},#!!! could be better... :value => lambda{|ts, v| result = v}, :exception => lambda{|ts, e| raise RemoteError, e}, :stderr => lambda{|ts, v| $stderr.puts(v); $stderr.flush}, :underlying => lambda{|ts, v| $stdout.puts(v); $stdout.flush}, }.freeze channel_value_acceptors = options.delete(:channel_value_acceptors) value_acceptor_channels = channel_value_acceptors ? channel_value_acceptors.keys : default_value_acceptor_channels channel_value_acceptors = Hash[value_acceptor_channels.collect{|ch| [ch, channel_value_acceptors && channel_value_acceptors[ch] ? channel_value_acceptors[ch] : default_channel_value_acceptors[ch]]}] channel_value_acceptors.reject!{|ch, acceptor| acceptor.nil?} remote_process(command, code, options).inject([]) do |history, (ch, timestamped_values)| timestamped_values.each do |ts, values| values.each do |v| history << [ts, [ch, v]] end end history end.sort.each do |ts, (ch, v)| acceptor = channel_value_acceptors[ch] acceptor.call(ts, v) if acceptor end block_given? ? (yield result) : (return result) end def self.rails_process_eval(command, code=nil, options={}) # options: :channel_value_acceptors, :rails_root (for remote_process), :rails_env (for remote_process), :rails_startup_code (for remote_process), :remote_here_doc_token (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :return_immediately (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :wait_timeout (for ChannelMultiplexer::BaseProtocol::remote_bootstrap) process_eval(command, code, options.merge(:load_rails=>true)) end def self.host_eval(hostname, code=nil, options={}) # options: :command_generator, :channel_value_acceptors (for process_eval), :load_rails (for remote_process), :rails_root (for remote_process), :rails_env (for remote_process), :rails_startup_code (for remote_process), :remote_here_doc_token (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :return_immediately (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :wait_timeout (for ChannelMultiplexer::BaseProtocol::remote_bootstrap) command = (options.delete(:command_generator) || lambda{|hostname| "ssh #{hostname.inspect} /usr/bin/env ruby"}).call(hostname) process_eval(command, code, options) end def self.rails_host_eval(hostname, code=nil, options={}) # options: :command_generator, :channel_value_acceptors (for process_eval), :rails_root (for remote_process), :rails_env (for remote_process), :rails_startup_code (for remote_process), :remote_here_doc_token (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :return_immediately (for ChannelMultiplexer::BaseProtocol::remote_bootstrap), :wait_timeout (for ChannelMultiplexer::BaseProtocol::remote_bootstrap) host_eval(hostname, code, options.merge(:load_rails=>true)) end end __END_REMOTE_OBJECT_MANAGER_SOURCE__ ).tap do |remote_object_manager_source| eval(remote_object_manager_source) RemoteObjectManager.const_set(:SOURCE, remote_object_manager_source) end =begin # EXAMPLE REMOTE CODE cm = nil begin cm = ChannelMultiplexer.new($stderr) cm.add_channel(:stdout, true, $stdout) cm.context(10, 11){|*args| args.each{|a| puts "*** #{a}"}; 'hi'} cm.context(1, 2, 3){|*args| args.each{|a| puts "+++ #{a}"}; raise StandardError.new('an exception')} cm.context{`grep xyzzy xyzzy`; puts "this is on $stdout"; $stderr.puts "this is on $stderr"; 'this is the return value'} rescue => e puts e puts e.backtrace ensure cm.close if cm end =end =begin #RemoteObjectManager::remote_process_bootstrap(command, RemoteObjectManager::SOURCE, $stdin) =end =begin #! /usr/bin/env ruby # === EXAMPLE REMOTE CODE INVOKATION === require "remote_object_manager" hostname = ARGV[0] ( RemoteObjectManager::host_eval hostname, <<-'END_CODE' value = (1..10).collect{|x| "#{`hostname`.strip} / #{`uname -a`.strip}: #{x*x}"} puts value.inspect value # lambda{} END_CODE ).tap do |result| result.each{|v| puts ">>> #{v}"} if result end =end
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) require "superpowers" require "minitest/autorun" require 'rails' require 'rails/generators' class TestApp < Rails::Application config.root = File.dirname(__FILE__) end Rails.application = TestApp module Rails def self.root @root ||= File.expand_path(File.join(File.dirname(__FILE__), '..', 'tmp', 'rails')) end end Rails.application.config.root = Rails.root Rails::Generators.configure! Rails.application.config.generators def copy_routes routes = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'routes.rb')) destination = File.join(Rails.root, "config") FileUtils.mkdir_p(destination) FileUtils.cp File.expand_path(routes), destination end def copy_models model = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'user.rb')) destination = File.join(Rails.root, "app", "models") FileUtils.mkdir_p(destination) FileUtils.cp File.expand_path(model), destination end def generator_list { rails: ['scaffold', 'controller', 'migration'], superpowers: ['scaffold'] } end def path_prefix(name) case name when :rails 'rails/generators' else 'generators' end end def require_generators(generator_list) generator_list.each do |name, generators| generators.each do |generator_name| if name.to_s == 'rails' && generator_name.to_s == 'mailer' require File.join(path_prefix(name), generator_name.to_s, "#{generator_name}_generator") else require File.join(path_prefix(name), name.to_s, generator_name.to_s, "#{generator_name}_generator") end end end end alias :require_generator :require_generators
class WorldMusicWorkshopRankService < ExperimentService class << self SONGS = 5 PAIRS = (0...SONGS).to_a.combination(3).to_a def create(options) raise NotFoundError.new('Experiment', 'Evaluation Not Finished') if Experiment.where( username: options['username'], model: 'WorldMusicWorkshopEvaluationEntry', )&.first.nil? DB.transaction do exp = Experiment.create( username: options['username'], model: 'WorldMusicWorkshopRankEntry', ) PAIRS.length.times.to_a.shuffle.each do |i| WorldMusicWorkshopRankEntry.create( experiment: exp, pair_id: i, ) end return WorldMusicWorkshopRankService.new(exp) end end def find(options) exp = Experiment.where( username: options['username'], model: 'WorldMusicWorkshopRankEntry', )&.first raise NotFoundError.new('Experiment', 'No Such Experiment Existed') if exp.nil? WorldMusicWorkshopRankService.new(exp) end def export Experiment.where( model: 'WorldMusicWorkshopRankEntry', ).map do |exp| offset = WorldMusicWorkshopRankService.new(exp).offset res = exp.entries.order(:pair_id).map do |pair| { song_a: PAIRS[pair.pair_id][0] + offset, song_b: PAIRS[pair.pair_id][1] + offset, song_c: PAIRS[pair.pair_id][2] + offset, option: pair.option, } end { username: exp.username, matrix: res, } end end end def initialize(entity) @entity = entity end def offset cat = @entity.username[0].to_i raise NotFoundError.new('Entity', 'No Such Category') unless (0...6).include?(cat) # 6 Groups @entity.username[0].to_i * WorldMusicWorkshopRankService.singleton_class::SONGS end def next entity = @entity.entries.where(edited: false).order(:id).first raise NotFoundError.new('Entity', 'Experiment Finished') if entity.nil? { id: entity.id, progress: @entity.entries.where(edited: true).count.to_f / @entity.entries.count, wavs: [ { label: 'A', entity: "/static/world_music_workshop/#{WorldMusicWorkshopRankService.singleton_class::PAIRS[entity.pair_id][0] + offset}.mp3", }, { label: 'B', entity: "/static/world_music_workshop/#{WorldMusicWorkshopRankService.singleton_class::PAIRS[entity.pair_id][1] + offset}.mp3", }, { label: 'C', entity: "/static/world_music_workshop/#{WorldMusicWorkshopRankService.singleton_class::PAIRS[entity.pair_id][2] + offset}.mp3", }, ], } end def update(options) entry = @entity.entries.where(id: options['id'])&.first raise NotFoundError.new('Entry Not Existed') if entry.nil? entry.option = options['option'] entry.edited = true entry.save nil end def destroy @entity.entries.delete @entity.delete end end
module InterestedController extend ActiveSupport::Concern def create @interest = interest_class.new(interest_params) if @interest.save notification_worker_class.perform_async(@interest.id) acknowledgement_worker_class.perform_async(@interest.id) flash[:notice] = create_notice else flash[:error] = create_error(@interest) end redirect_to root_path end private def create_notice "Thanks for your interest. We'll be in touch." end def create_error(interest) error = "There were errors in your form. " error << interest.errors.full_messages.collect { |e| e + "." }.join(" ") end def interest_class controller_name.classify.constantize end def interest_params params.require(interest_class.model_name.singular_route_key).permit(:name, :email, :content) end def interest_prefix controller_name.gsub(/_interests/,"").camelize end def notification_worker_class (interest_prefix + "InterestNotificationWorker").constantize end def acknowledgement_worker_class (interest_prefix + "InterestAcknowledgementWorker").constantize end end
require 'dumped_api/operation' require 'dumped_api/import' module DumpedApi module Operations module GitRepos class Query < DumpedApi::Operation include Import['repositories.git_repos'] def call(params = {}) if language = params['language'] git_repos.by_language(language) else git_repos.all end end end end end end
require "rails_helper" RSpec.describe "Login Page" do before(:each) do @user = User.create!(name: "Elah Pillado", address: "123 Chase Rd", city: "Marietta", state: "GA", zip: 30008, email: "elah@email.com", password: "password", role: 0) @merchant = User.create!(name: "Sinai Pillado", address: "123 Chase Rd", city: "Marietta", state: "GA", zip: 30008, email: "sinai@email.com", password: "password", role: 1) @admin = User.create!(name: "Nelcy Pillado", address: "123 Kedvale Ave", city: "Chicago", state: "IL", zip: 60623, email: "nelcy@email.com", password: "password", role: 2) end it "If I am a regular user, I am redirected to my profile page. A flash message will confirm I am logged in." do visit "/login" fill_in :email, with: @user.email fill_in :password, with: @user.password click_button "Log In" expect(current_path).to eq("/profile") expect(page).to have_content("You are now logged in!") end it "If I am a merchant employee, I am redirected to my merchant dashboard. A flash message will confirm I am logged in." do visit "/login" fill_in :email, with: @merchant.email fill_in :password, with: @merchant.password click_button "Log In" expect(current_path).to eq("/merchant") expect(page).to have_content("You are now logged in!") end it "If I am an admin user, I am redirected to my admin dashboard. A flash message will confirm I am logged in." do visit "/login" fill_in :email, with: @admin.email fill_in :password, with: @admin.password click_button "Log In" expect(current_path).to eq("/admin") expect(page).to have_content("You are now logged in!") end it "User cannot log in with bad credentials." do visit "/login" password = "Cool123" fill_in :email, with: @user.email fill_in :password, with: password click_button "Log In" expect(current_path).to eq("/login") expect(page).to have_content("Uh oh... Wrong email or password. Please try again!") end it "Regular users who are logged in already are redirected to profile page." do visit "/login" fill_in :email, with: @user.email fill_in :password, with: @user.password click_button "Log In" expect(current_path).to eq("/profile") visit "/login" expect(current_path).to eq("/profile") expect(page).to have_content("You're already logged in!") # expect(page).to_not have_link("Log In") # expect(page).to_not have_link("Register") end it "Merchant employees who are logged in already are redirected to their merchant dashboard." do visit "/login" fill_in :email, with: @merchant.email fill_in :password, with: @merchant.password click_button "Log In" expect(current_path).to eq("/merchant") visit "/login" expect(current_path).to eq("/merchant") expect(page).to have_content("You're already logged in!") # expect(page).to_not have_link("Log In") # expect(page).to_not have_link("Register") end it "Admin users who are logged in already are redirected to their admin dashboard." do visit "/login" fill_in :email, with: @admin.email fill_in :password, with: @admin.password click_button "Log In" expect(current_path).to eq("/admin") visit "/login" expect(current_path).to eq("/admin") expect(page).to have_content("You're already logged in!") # expect(page).to_not have_link("Log In") # expect(page).to_not have_link("Register") end end
class CategoryService class << self include ApiClientRequests STATIC_SUPER_CATS = [ 'womens-fashion-accessories', 'mens-fashion-accessories', 'kids-babies', 'shoes-footwear', 'bags-luggage', 'beauty-health', 'computers-electronics' ] def fetch(params = {}) @search_params = params.dup # Currently this class talks to the products API rather than the # categories API so does not need this flag. @search_params.delete(:product_mapable) get_categories end def build(json_response) body = if json_response.respond_to?(:body) json_response.body else json_response end if body.respond_to?(:map) body.map do |json_object| Category.new(json_object) end else Category.new(body) end end def category_mappings categories = self.find(hierarchy_level: 3) categories.inject({}) do |category_hash, super_category| category_hash[super_category.code] = "super_cat" super_category.children.each do |category| category_hash[category.code] = "category" category.children.each do |sub_category| category_hash[sub_category.code] = "sub_category" end end category_hash end end private def get_categories # Get super category data from product service super_cats = facet_from_fetch('super_cat', ProductService.fetch(@search_params.merge({rows: 0}))) return [] if super_cats.blank? Parallel.map(STATIC_SUPER_CATS, :in_threads => 4) do |super_cat| # Get each super category category = super_cats.find{|sc| sc.code == super_cat } next if category.nil? # Get children categories children = ProductService.fetch(@search_params.merge({rows: 0, super_cat: super_cat})) # Tack on the children of said super category category[:children] = facet_from_fetch('category', children) || [] Parallel.each(category[:children], :in_threads => 4)do |c| children = ProductService.fetch(@search_params.merge({rows: 0, category: c.code})) sub_categories = facet_from_fetch('sub_category', children) c[:children] = sub_categories.nil? ? [] : sub_categories end # Implicit return category end.reject{|c| c.nil? } end def facet_from_fetch(facetName, results) results.facets.find{ |f| f.field == facetName }.try '[]', 'values' end end end
namespace :deploy do desc 'Compile assets' task :compile_assets => [:set_hanami_env] do on release_roles(fetch(:assets_roles)) do within release_path do with hanami_env: fetch(:hanami_env) do execute :hanami, 'assets precompile' end end end end after 'deploy:updated', 'deploy:compile_assets' end # we can't set linked_dirs in load:defaults, # as assets_prefix will always have a default value namespace :deploy do task :set_linked_dirs do set :linked_dirs, fetch(:linked_dirs, []).push('public/assets').uniq end end after 'deploy:set_hanami_env', 'deploy:set_linked_dirs' namespace :load do task :defaults do set :assets_roles, fetch(:assets_roles, [:web]) end end
require "rails_helper" describe Candidate do let(:candidate){ FactoryGirl.create(:candidate) } it "is valid" do expect(candidate.valid?).to eq(true) end it "sanitizes the twitter_name" do expect(candidate.twitter_name).to eq("joe0") end it "has a token" do expect(candidate.token).to_not be_nil end end
class AddCmcToCards < ActiveRecord::Migration[5.1] def change add_column :cards, :cmc, :integer add_column :cards, :set, :string end end
class SuportMailer < ApplicationMailer include ApplicationHelper def deliver_survey_mail_message recipient @recipient = recipient survey = recipient.survey mail_message = survey.mail_message recipient_data = survey.users_data[recipient.email] reply_link = build_reply_link_for_recipient recipient recipient_data["reply_link"] = reply_link @content = translate_tags(recipient_data, mail_message.content.dup) subject = translate_tags recipient_data, mail_message.subject.dup recipient.update(sended: true) from = survey.mail_config_from mail(:from => from, :to => recipient.email, :subject => subject, delivery_method: :mailgun) # mail = mail(:from => Rails.application.secrets.gmail_smtp[:user_name] ,:to => recipient.email, :subject => subject, delivery_method: :smtp) # mail.delivery_method # mail.delivery_method.settings.merge!(Rails.application.secrets.gmail_smtp) end end
class CreateScenics < ActiveRecord::Migration def change create_table :scenics do |t| t.string :name, null:false t.string :picture, null:false t.string :manager_name, null:false t.string :manager_number, null: false t.integer :sys_admin_id t.timestamps null: false end end end
class Post < ActiveRecord::Base belongs_to :user belongs_to :parent, class_name: 'Post' has_many :replies, class_name: 'Post', foreign_key: :parent_id def self.roots where(parent_id: nil) end end
# -*- mode: ruby -*- # vi: set ft=ruby : require 'yaml' project_config = {} begin project_config = YAML.load_file('vagrant.yaml'); rescue Errno::ENOENT project_config = { name: nil, password: nil, ip: nil, url: nil } end # Run on first load, or if these are not set. if project_config['name'] == nil puts "Enter a project name" project_config['name'] = STDIN.gets.chomp system("vagrant plugin install vagrant-triggers"); end if project_config['password'] == nil puts "Enter a password to use for MySQL" project_config['password'] = STDIN.gets.chomp end if project_config['ip'] == nil puts "Enter a vacant IP Address (the last 3 digits only)" project_config['ip'] = "192.168.50." + STDIN.gets.chomp end if project_config['url'] == nil puts "Enter a development URL without http:// and .dev will be appended automatically." project_config['url'] = STDIN.gets.chomp end File.open('vagrant.yaml', 'w') do |f| f.sync = true f.write project_config.to_yaml end Vagrant.configure(2) do |config| project_config = YAML.load_file('vagrant.yaml') config.vm.box = "bento/ubuntu-16.04" config.vm.network "private_network", ip: project_config['ip'].to_s, guest: 80, host: 8080, auto_correct: true config.vm.network "public_network", guest: 80, host: 8080, auto_correct: true, :netmask => '255.255.255.0' config.vm.provision :shell, path: "bootstrap.sh", privileged: false, args: [project_config['name'].to_s, project_config['password'].to_s] config.vm.synced_folder ".", "/var/www/vhosts/" + project_config['name'].to_s, owner: "vagrant", group: "www-data", mount_options: ["dmode=777,fmode=777"] config.trigger.after [:up] do system("echo " + project_config['ip'].to_s + " " + project_config['url'].to_s + " | sudo tee -a /etc/hosts") end config.trigger.after [:halt, :destroy] do # Removes the host from the /etc/hosts file system("sudo sed '/" + project_config['ip'].to_s + " " + project_config['url'].to_s + "/d' /etc/hosts >> /dev/null") end config.trigger.after [:destroy] do # Resets the project config project_config['name'] = nil project_config['password'] = nil project_config['url'] = nil project_config['ip'] = nil File.open('vagrant.yaml', 'w') do |f| f.write project_config.to_yaml end end config.trigger.after [:up, :provision, :reload] do print(%{ :::::::-. ... :::. :::..,:::::: ;;, `';, .;;;;;;;.`;;;;, `;;;;;;;'''' `[[ [[,[[ \[[,[[[[[. '[[ [[cccc $$, $$$$$, $$$$$$ "Y$c$$ $$"""" 888_,o8P'"888,_ _,88P888 Y88 888oo,__ MMMMP"` "YMMMMMP" MMM YM """"YUMMM Welcome to the future. }) system('echo " ip: "' + project_config['ip']) system('echo " url:"' + project_config['url']) print(%{ }) end config.trigger.after [:halt] do print(%{ ::: . ::: ::: ::: .,:::::::::::::-. ;;; .;;,.;;; ;;; ;;; ;;;;'''' ;;, `';, [[[[[/' [[[ [[[ [[[ [[cccc `[[ [[ _$$$$, $$$ $$' $$' $$"""" $$, $$ "888"88o, 888o88oo,.__o88oo,.__888oo,__ 888_,o8P' MMM "MMP"MMM""""YUMMM""""YUMMM""""YUMMMMMMMP"` It's been nice. }) system('echo " ip: "' + project_config['ip']) system('echo " url:"' + project_config['url']) print(%{ }) end config.vm.provider "virtualbox" do |vb| vb.memory = "1024" end end
class ChangeCompetitionPrivateToStatus < ActiveRecord::Migration[4.2] def up add_column :competitions, :status, :integer, null: false, default: 0 Competition.find_each do |comp| comp.status = comp.private? ? 0 : 1 end remove_column :competitions, :private end def down add_column :competitions, :private, :boolean, null: false Competition.find_each do |comp| comp.private = (comp.status == 0) end remove_column :status, :private end end
class Room attr_reader :name, :capacity, :rate, :price attr_accessor :songs_available, :current_guests def initialize(name, capacity, current_guests, price, songs_available) @name = name @capacity = capacity @current_guests = current_guests @price = price @songs_available = songs_available end def add_song(song) @songs_available << song end def get_room_price return @price end def capacity_check @capacity > @current_guests.count end end
# frozen_string_literal: true module Response class Base attr_reader :data def initialize(data = {}) @data = data end def success? self.class.name == 'Response::Success' end end end
#Site5 specific stuff set :use_sudo, false set :group_writable, false # Less releases, less space wasted set :keep_releases, 2 # The mandatory stuff set :application, "lafacroft" set :user, "lafacrof" #Git info default_run_options[:pty] = true set :repository, "git://github.com/chipmunk884/Lafacroft.git" set :scm, "git" set :branch, "master" #set :deploy_via, :remote_cache # This is related to site5 too. set :deploy_to, "/home/#{user}/#{application}" role :app, "lafacroft.com" role :web, "lafacroft.com" role :db, "lafacroft.com", :primary => true # Create Site5 specific tasks namespace :deploy do desc "Deploy app, run migrations, and start Phusion Passenger" task :cold do update site5::link_public_html restart end desc "Restart Phusion Passenger" task :restart do run "touch #{current_path}/tmp/restart.txt" end desc "Start application -- not needed for Passenger" task :start, :roles => :app do #nothing, needs to be blank to make Passenger work properly end namespace :site5 do desc "Link the public folder of the application to public_html" task :link_public_html do run "cd /home/#{user}; rm -rf public_html; ln -s #{current_path}/public ./public_html" end end end
class OphtalmologyTemplates::TemplateFilesController < TemplateFilesController before_action :set_fileable private def set_fileable @fileable = OphtalmologyTemplate.find(params[:ophtalmology_template_id]) authenticate_doctor_for_template(@fileable) end end
require "scheme_maker_ext" module SchemeMaker class SchemeGenerator end class MaterialInfo attr_reader :color, :id def initialize(color, id) @color = color @id = id end end class CrossStitchSchemeGenerator end class SquareCellInfo attr_reader :size def initialize(size) @size = size end end end
require 'digest/md5' require 'digest/sha1' puts "Введите слово или фразу для шифрования:" # Ввод слова для шифровки word = STDIN.gets.chomp puts "Каким способом зашифровать:\n"\ "1. MD5\n"\ "2. SHA1" # Ввод варианта шифровки answer = STDIN.gets.to_i # .between? - между значениями (min, max) # until - выполняет пока условие ложно until answer.between?(1, 2) puts 'Выберите 1 или 2' answer = STDIN.gets.to_i end puts "Вот что получилось: " # Проверяем какую шифровку выбрал пользователь case answer when 1 # Вывод слова в шифровке MD5 puts Digest::MD5.hexdigest(word) when 2 # Вывод слова в шифровке SHA1 puts Digest::SHA1.hexdigest (word) end
# -*- encoding : utf-8 -*- class CreatePayments < ActiveRecord::Migration def change create_table :payments do |t| t.date :data, null: false t.time :time, null: false t.decimal :value, precision: 6, scale: 2, null: false t.integer :user_id, null: false t.string :comment t.integer :status, :default => 0, null: false t.timestamps end add_index :payments, [:user_id, :created_at] end end
require 'rails_helper' RSpec.describe Company, type: :model do before { @company = FactoryGirl.build :company } subject { @company } @company_attributes = [:email, :password, :password_confirmation, :name, :phonenumber, :auth_code] it { should be_valid } # model should respond to attributes @company_attributes.each do |attribute| it { should respond_to attribute } end # test presence of attributes [:email, :password].each do |attribute| it { should validate_presence_of attribute } end describe "test number format of phonenumber" do context "when phonenumber is set to string containing string" do before { @company.phonenumber = "some string" } it "@company should be invalid" do expect(@company).not_to be_valid end end context "when phonenumber is set to string containing numbers" do before { @company.phonenumber = "0204704427" } it "@company should be valid" do expect(@company).to be_valid end end end # test has_many association it { should have_many :requirements } end
require "clockwork" require "timecop" require "clockwork/test/event" require "clockwork/test/job_history" require "clockwork/test/manager" require "clockwork/test/version" require "clockwork/test/rspec/matchers" module Clockwork module Methods def every(period, job, options={}, &block) ::Clockwork.manager.every(period, job, options, &block) ::Clockwork::Test.manager.every(period, job, options, &block) end def configure(&block) ::Clockwork.manager.configure(&block) ::Clockwork::Test.manager.configure(&block) end def handler(&block) ::Clockwork.manager.handler(&block) ::Clockwork::Test.manager.handler(&block) end def on(event, options={}, &block) ::Clockwork.manager.on(event, options, &block) ::Clockwork::Test.manager.on(event, options, &block) end end module Test class << self def included(klass) klass.send "include", Methods klass.extend Methods klass.send "include", ::Clockwork::Methods klass.extend ::Clockwork::Methods end def manager @manager ||= Clockwork::Test::Manager.new end def manager=(manager) @manager = manager end end module Methods def run(opts = {}) file = opts[:file] || "./config/clock.rb" run_opts = { max_ticks: opts[:max_ticks], start_time: opts[:start_time], end_time: opts[:end_time], tick_speed: opts[:tick_speed] } manager.run(run_opts) do # TODO parse file rather than loading it # and overloading Clockwork::Methods::every # and Clockwork::Methods::configure load file end end def clear! Clockwork::Test.manager = Clockwork::Test::Manager.new end def ran_job?(job) manager.ran_job?(job) end def times_run(job) manager.times_run(job) end def block_for(job) manager.block_for(job) end end extend Methods, ::Clockwork::Methods end end
class Customer < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :purchases, dependent: :nullify include JpPrefecture jp_prefecture :prefecture_code validates :name, presence: true VALID_PHONE_REGEX = /\A(((0(\d{1}[-(]?\d{4}|\d{2}[-(]?\d{3}|\d{3}[-(]?\d{2}|\d{4}[-(]?\d{1}|[5789]0[-(]?\d{4})[-)]?)|\d{1,4}\-?)\d{4}|0120[-(]?\d{3}[-)]?\d{3})\z/ validates :tel, presence: true, format: { with: VALID_PHONE_REGEX } before_save { self.email = email.downcase } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, {presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }} validates :postcode, presence: true validates :prefecture_code, presence: true validates :address_city, presence: true validates :address_street, presence: true validates :password_confirmation, presence: true def prefecture_name JpPrefecture::Prefecture.find(code: prefecture_code).try(:name) end def prefecture_name=(prefecture_name) self.prefecture_code = JpPrefecture::Prefecture.find(name: prefecture_name).code end end
require File.dirname(__FILE__) + '/../spec_helper' describe FactoryGirl::Generate do before(:each) do @it = FactoryGirl::Generate.new end it "should return example value for number" do @it.value_for(User.columns_hash["number"]).should eql('1') end it "should return example value for string" do @it.value_for(User.columns_hash["username"]).should eql('"Value for username"') end it "should return example value for datetime" do @it.value_for(Post.columns_hash["created_at"]).should eql('{ Time.now }') end it "should return example value for date" do @it.value_for(Post.columns_hash["starts_on"]).should eql('{ Time.now.to_date }') end it "should render factory for user" do FactoryGirl::Generate.new.render_factory_for(User).should eql(%Q[Factory.define :user do |u| u.number 1 u.username "Value for username" u.password "Value for password" end]) end it "should not render updated_at and created_at" do @it.render_factory_for(Post).should_not match(/updated_at|created_at/) end end
source 'https://rubygems.org' git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") "https://github.com/#{repo_name}.git" end # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.2.2' # Improves performance of booting the application gem 'bootsnap', require: false # Use sqlite3 as the database for Active Record gem 'sqlite3', '~> 1.3.6' # Use Puma as the app server gem 'puma', '~> 4.0' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.2' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.5' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 3.0' # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Capistrano for deployment group :development do gem 'capistrano', '~> 3.7', '>= 3.7.1' gem 'capistrano-rails', '~> 1.2' gem 'capistrano-passenger', '~> 0.2.0' gem 'capistrano-rvm' end group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platform: :mri end group :development do # Access an IRB console on exception pages or by using <%= console %> anywhere in the code. gem 'web-console', '>= 3.3.0' gem 'listen', '~> 3.0.5' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] # User authentication gem 'devise' # Bootstrap framework gem 'bootstrap-sass' gem 'bootstrap_form' gem 'bootswatch-rails' # Automatically add vendor prefixes to css gem 'autoprefixer-rails' # PDF generation based on HTML, for export. gem 'wicked_pdf' gem 'wkhtmltopdf-binary', group: :production # Permission management gem 'cancancan' # Bibliography export/import and reference styling gem 'citeproc-ruby' gem 'bibtex-ruby' gem 'csl-styles' # Markdown parsing and rendering gem 'redcarpet' # Tag selection gem 'selectize-rails' # Color picker gem 'jquery-minicolors-rails' # Breadcrumbs gem 'breadcrumbs_on_rails' # Security testing group :development do gem 'brakeman' gem 'bundler-audit' end # Image processing gem 'mini_magick' # PostgreSQL database adapter used both in development and production gem 'pg', group: [:production, :development] # Bulk insert statements gem 'activerecord-import' # Validations for ActiveStorage file attachments gem 'file_validators' # Dropzone for file uploads gem 'dropzonejs-rails' # Parsing references gem 'anystyle' # Integrate premailer with actionmailer to inline css gem 'actionmailer_inline_css' gem 'letter_opener', group: :development # Transactional email API gem 'mailgun-ruby'
class HomeController < ApplicationController layout 'landing_page' def index @servers = Server.all if user_signed_in? redirect_to dashboard_path else end end end
require 'rails_helper' RSpec.describe User, type: :model do context "With valid attributes" do it "should save" do user = User.new( first_name: 'shane', last_name: 'chang', email: 'schang@codingdojo.com' ) expect(user).to be_valid end end context "With invalid attributes" do it "should not save if first_name field is blank" do user = User.new( first_name: "", last_name: 'chang', email: 'schang@codingdojo.com') expect(user).to be_invalid end # +++++++++++++++++++++++++++++++++++++++++++++++++++ it "should not save if last_name field is blank" do user2 = User.new( first_name: "asdsd", last_name: '', email: 'schang@codingdojo.com') expect(user2).to be_invalid end #++++++++++++++++++++++++++++++++++++++++++++++++++++ it "should not save if email already exists" do user3 = User.new(first_name:"Ali", last_name:"asd", email:"schang@codingdojo.com") user3.save user4 = User.new( first_name: "asdsd", last_name: 'asdads ', email: 'schang@codingdojo.com') expect(user4).to be_invalid end #++++++++++++++++++++++++++++++++++++++++++++++++ it "should contain a valid email" do user5 = User.new(first_name:"Ali", last_name:"asd", email:"schang@codingdojo") expect(user5).to be_invalid end end #end of context end
require 'rails_helper' RSpec.describe ContactService::IndexContact, type: :service do let(:user) { create(:user) } let(:contact) { create(:contact) } let(:csv_file) { FilesTestHelper.csv } context "when there are no contacts" do it "returns no contacts" do expect(described_class.call(user, nil).result).to be_empty end end context "when there are contacts" do it "returns a list of contacts" do expect(described_class.call(contact.user, nil).result).to contain_exactly(contact) end end end
=begin Write a method that takes a string, and returns a new string in which every character is doubled. Examples =end def repeater(str) new_array = [] str.chars.each { |chr| new_array << (chr * 2)} new_array.join end puts repeater('Hello') == "HHeelllloo" puts repeater("Good job!") == "GGoooodd jjoobb!!" puts repeater('') == ''
RSpec.describe Telegram::Bot::UpdatesController::Testing do include_context 'telegram/bot/updates_controller' let(:controller_class) do Class.new(Telegram::Bot::UpdatesController) do attr_accessor :ivar end end describe '#recycle!' do subject { -> { controller.recycle!(full) } } before do controller.ivar = :ival session[:key] = 'sval' end let(:full) {} it { should_not change(controller, :ivar).from :ival } it { should_not change { controller.send(:session)[:key] }.from 'sval' } context 'when full is true' do let(:full) { true } it { should change(controller, :ivar).from(:ival).to nil } it { should change { controller.instance_variable_defined?(:@ivar) }.to false } it { should_not change { controller.send(:session)[:key] }.from 'sval' } end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.box = "scotch/box" config.vm.network "private_network", ip: "192.168.12.34" config.vm.hostname = "scotchbox" config.vm.synced_folder ".", "/var/www", :mount_options => ["dmode=777", "fmode=666"] config.vm.synced_folder "../_hdd/projects/web/.", "/var/www/html", :mount_options => ["dmode=777", "fmode=666"] config.vm.synced_folder "../_hdd/projects/rails/.", "/var/www/rails", :mount_options => ["dmode=777", "fmode=666"] # Optional NFS. Make sure to remove other synced_folder line too #config.vm.synced_folder ".", "/var/www", :nfs => { :mount_options => ["dmode=777","fmode=666"] } config.ssh.forward_agent = true config.ssh.username = "vagrant" config.ssh.password = "vagrant" config.ssh.private_key_path = ["~/.ssh/id_rsa", "~/.vagrant.d/insecure_private_key"] config.vm.provision "file", source: "~/.ssh/id_rsa.pub", destination: "~/.ssh/authorized_keys" config.vm.provision "shell", inline: <<-EOC sudo sed -i -e "\\#PasswordAuthentication yes# s#PasswordAuthentication yes#PasswordAuthentication no#g" /etc/ssh/sshd_config sudo service ssh restart EOC config.vm.provider 'virtualbox' do |v| # v.memory = 1024 v.memory = 1530 v.cpus = 3 end end
class ProfileCompCardsController < ApplicationController before_action :set_profile, only: [:index] def index json_response({ :profile_comp_card => { id: @profile_comp_card.id, comp_card_type: @profile_comp_card.comp_card_type, profile_comp_card_photos: @profile_comp_card.profile_comp_card_photo.map { |p| ({ id: p.profile_photo_id, sequence: p.sequence, })}, profile_comp_card_items: @profile_comp_card.profile_comp_card_item.map { |p| ({ id: p.profile_item_type_id, sequence: p.sequence, })}, } }) end def saveCompCard if params[:profile_id].present? and params[:comp_card_type].present? @profile_comp_card = ProfileCompCard.find_by(:profile_id => params[:profile_id]) @profile_comp_card.update(:comp_card_type => params[:comp_card_type]) if params[:comp_card_photos].present? @profile_comp_card.profile_comp_card_photo.clear() params[:comp_card_photos].each do |index2, photo| @profile_comp_card.profile_comp_card_photo.create(profile_photo_id: photo[:id], sequence: photo[:sequence]) end end if params[:comp_card_items].present? @profile_comp_card.profile_comp_card_item.clear() params[:comp_card_items].each do |index2, item| @profile_comp_card.profile_comp_card_item.create(profile_item_type_id: item[:id], sequence: item[:sequence]) end end end end private def set_profile @profile = Profile.find(params[:profile_id]) @profile_comp_card = ProfileCompCard.includes([:profile_comp_card_item, :profile_comp_card_photo]).find_by(:profile_id => @profile.id) if @profile if @profile_comp_card.nil? @profile_comp_card = @profile.create_profile_comp_card!(:comp_card_type => 1) end end end
# To change this template, choose Tools | Templates # and open the template in the editor. require 'rexml/document' require 'rubygems' require 'sqlite3' require 'inifile' module Bnicovideo class UserSession module MacOsX def self.init_from_firefox base_path = File.join(ENV['HOME'], 'Library', 'Application Support', 'Firefox') ini_path = File.join(base_path, 'profiles.ini') ini_hash = IniFile.load(ini_path).to_h profile_path = nil ini_hash.each do |k, v| next unless v['Name'] == 'default' relative = (v['IsRelative'] != '0') input_path = v['Path'] if relative profile_path = File.join(base_path, input_path) else profile_path = input_path end sql_path = File.join(profile_path, 'cookies.sqlite') conn = SQLite3::Database.new(sql_path) val = conn.get_first_value("select value from moz_cookies" + " where host='.nicovideo.jp' AND name='user_session'") return val end return nil end def self.init_from_chrome sql_path = File.join(ENV['HOME'], 'Library', 'Application Support', 'Google', 'Chrome', 'Default', 'Cookies') conn = SQLite3::Database.new(sql_path) val = conn.get_first_value("select value from cookies" + " where host_key='.nicovideo.jp' AND name='user_session'") conn.close return val end def self.init_from_safari cookie_base_path = File.join(ENV['HOME'], 'Library', 'Cookies') bcpath = File.join(cookie_base_path, 'Cookies.binarycookies') if File.exist?(bcpath) cookie_path = bcpath bin = nil File.open(cookie_path, 'rb') do |file| bin = file.read end raise 'Invalid Cookie file' unless bin[0..3] == 'cook' page_num = bin[4..7].unpack('N')[0] pages_length = [] page_num.times do |i| page_length = bin[(8 + i * 4)..(11 + i * 4)].unpack('N')[0] pages_length.push(page_length) end read_ptr = 8 + page_num * 4 pages_length.each do |pgl| page = bin[read_ptr..(read_ptr + pgl - 1)] cookies_num = page[4..7].unpack('V')[0] nread_ptr = read_ptr cookies_offset = [] cookies_num.times do |i| cookie_offset = page[(8 + i * 4)..(11 + i * 4)].unpack('V')[0] cookies_offset.push(cookie_offset) end nread_ptr += 12 + cookies_num * 4 read_ptr += pgl cookies_offset.each do |cof| cookie_length = page[cof..(cof + 3)].unpack('V')[0] cookie_bin = page[cof..(cof + cookie_length - 1)] offset_url = page[(cof + 16)..(cof + 19)].unpack('V')[0] offset_name = page[(cof + 20)..(cof + 23)].unpack('V')[0] offset_path = page[(cof + 24)..(cof + 27)].unpack('V')[0] offset_value = page[(cof + 28)..(cof + 31)].unpack('V')[0] url_end = (/\x00/ =~ cookie_bin[offset_url..-1]) url = cookie_bin[offset_url, url_end] name_end = (/\x00/ =~ cookie_bin[offset_name..-1]) name = cookie_bin[offset_name, name_end] path_end = (/\x00/ =~ cookie_bin[offset_path..-1]) path = cookie_bin[offset_path, path_end] value_end = (/\x00/ =~ cookie_bin[offset_value..-1]) value = cookie_bin[offset_value, value_end] return value if (/nicovideo\.jp$/ =~ url) && (name == 'user_session') end end return nil else xml = REXML::Document.new(File.read(File.join(cookie_base_path, 'Cookies.plist'))) xml.root.elements.each('array/dict') do |elem| if elem.elements['key[text()="Domain"]'] && elem.elements['key[text()="Domain"]'].next_element && elem.elements['key[text()="Domain"]'].next_element.text == '.nicovideo.jp' && elem.elements['key[text()="Name"]'] && elem.elements['key[text()="Name"]'].next_element && elem.elements['key[text()="Name"]'].next_element.text == 'user_session' return elem.elements['key[text()="Value"]'].next_element.text end end return nil end end end end end
class UserBlock < ActiveRecord::Base belongs_to :user enum status: [:active, :warning, :block] end
class AddExtraScreeningFields < ActiveRecord::Migration def change add_column :screenings, :subtitles, :string, array: true, default: [] end end
require "papa_carlo/version" require "fileutils" require "erb" module PapaCarlo extend self def root @root ||= begin File.expand_path("../../", __FILE__) end end def create_project(project) FileUtils.mkdir_p("#{project}/lib/#{project}") FileUtils.mkdir_p("#{project}/config/options") FileUtils.mkdir_p("#{project}/spec/#{project}") FileUtils.mkdir_p("#{project}/spec/helpers") gemfile = File.join(root, "lib", "papa_carlo", "templates", "Gemfile") rakefile = File.join(root, "lib", "papa_carlo", "templates", "Rakefile") boot = File.join(root, "lib", "papa_carlo", "templates", "boot.erb") project_file = File.join(root, "lib", "papa_carlo", "templates", "project.erb") spec_helper = File.join(root, "lib", "papa_carlo", "templates", "spec_helper.rb") FileUtils.cp(gemfile, "#{project}/") FileUtils.cp(rakefile, "#{project}/") FileUtils.cp(spec_helper, "#{project}/spec/") @project_name = project @project_class = project.split("_").map(&:capitalize).join File.open("./#{project}/lib/#{project}.rb", "w") do |f| f << ERB.new(File.read(project_file)).result(binding) end File.open("./#{project}/config/boot.rb", "w") do |f| f << ERB.new(File.read(boot)).result(binding) end FileUtils.touch("./#{project}/config/options/config.yml") end end
class TasksController < ApplicationController def index @task_group = TaskGroup.find(params[:id]) @tasks= @task_group.tasks.all end def create @task_group = TaskGroup.find(params[:task_group_id]) @task_group = if @task = @task_group.tasks.create(params[:task]) redirect_to task_group_path(@task_group) else render :action => "new", :alert => 'Task couldnot be added. Try again' end end def new @task_group = TaskGroup.find(params[:task_group_id]) @task = @task_group.tasks.new end def edit @task = Task.find(params[:id]) @task_group = @task.task_group end def show @people = Person.all @task = Task.find(params[:id]) @task_group= @task.task_group @connections = Connection.where(:task_id => @task.id) end def update @task = Task.find(params[:id]) if @task.update_attributes(params[:task]) redirect_to task_path(@task), :notice => "Task Updated Successfully" else redirect_to :action => "edit", :alert => "Task Update Failed!!" end end def assignment @task = Task.find(params[:task_id]) @task_group = @task.task_group @person = Person.find(params[:people]) Connection.find_or_create_by_task_id_and_person_id(:task_id => @task.id, :person_id => @person.id) redirect_to task_group_task_path(@task_group, @task), :notice => @task.name + " with id " + @task.id.to_s + " is now assigned to " + @person.name end def release @task = Task.find(params[:task_id]) @person = Person.find(params[:person_id]) Connection.delete_all(:task_id => @task.id, :person_id => @person.id) flash[:alert]= "#{@person.name} has been released form Task: #{@task.name}" redirect_to person_path(@person) end end
class CommentSerializer < ActiveModel::Serializer attributes :id, :author_name, :user_id, :body, :created_at, :updated_at def author_name object.author.email if object.user_id end end
require 'spec_helper' require './app/models/link' feature "view list of links" do scenario "User can view a list of links on the homepage" do Link.create(url: 'http://www.makersacademy.com' , title: 'Makers Academy') visit '/links' expect(page.status_code).to eq 200 within 'ul#links' do expect(page).to have_content('Makers Academy') end end end
# More on Loops in Ruby k = 100 puts "The variable before the for loop k = #{k}" ## Basic For Loop in Ruby numbers = [3, 5 ,7] for k in numbers puts k end puts "You can still output the variable outside the for loop block of code. k = #{k}" ## Getting Index with Each colors = ["Red", "Blue", "Green", "Yellow"] colors.each_with_index do |color, index| puts "Moving on to index number #{index}" puts "The current color is #{color}" end ## Another Loop Example array_one = [1, 2, 3, 4, 5] array_one.each_with_index do |x, y| puts "For index number #{y} with its value #{x} is = #{x + y}" end ## Another Loop Example in a Method array_two = [10, 20, 30, 40, 50] def double(array) array.each_with_index do |element, index| result = element + element puts "Double the value of the element in index number #{index} is #{result}" end end double(array_two) ## Another Loop Example using a Method and a Conditional array_three = [-1, 2, 1, 2, 5, 7, 3] def print_if(array) array.each_with_index do |number, index| if index > number puts "We have a match. The index is #{index} and the number is #{number}!" puts "The result of multiplying them is #{index * number}" end end end print_if(array_three) ## Using .collect() array_four = [11, 22, 33, 44, 55] squares = array_four.collect {|number| number ** 2} p squares ## Using .map() array_five = [105, 73, 40, 18, -2] celsius_temp = array_five.map do |x| minus32 = x - 32 minus32 * (5.0/9.0) end p celsius_temp ## Another Example in a method array_six = [3, 8, 11, 15, 89] def cubes(array) array.map {|number| number ** 3} end p cubes(numbers) p cubes ([10, 43, 22, 100])
def hipsterfy(str) idx = str.rindex(/[aeiou]/) if idx.nil? str elsif idx < str.length - 1 str[0...idx] + str[(idx + 1)...str.length] else str[0...idx] end end def vowel_counts(str) result = Hash.new(0) vowels = "aeiou" arr = str.chars.select do |letter| vowels.include?(letter.downcase) end arr.each {|ch| result[ch.downcase] += 1} result end def caesar_cipher(str, num) alphabet = ("a".."z").map {|ch| ch} num %= 26 arr = str.chars.map do |letter| if alphabet.include?(letter.downcase) idx = (alphabet.index(letter) + num) idx -= 26 if idx >= alphabet.length alphabet[idx] else letter end end arr.join end # p caesar_cipher("str", 4)
class AddInvoiceMeasureUnit < ActiveRecord::Migration def self.up add_column :invoice_items, :measure, :string end def self.down remove_column :invoice_items, :measure end end
class BackendController < ApplicationController def index puts "Showing Backend Menu" end end
require 'cosmicrawler' require 'kconv' require 'string-scrub' require 'nokogiri' require 'natto' class StaticPagesController < ApplicationController @@mecab = Natto::MeCab.new def home end def list_uris file = params[:file] if file.nil? @fine_name = "ファイルが選択されていません" @uris = [] else @file_name = file.original_filename @uris = URI::extract(file.read, ['http', 'https']) end end def calc_word_frequency GC.start uri = params[:uri] @word_frequency = {} if uri.nil? render nothing: true, status: 400 and return end Cosmicrawler.http_crawl([uri]) do |request| get = request.get status = get.response_header.status if status == 200 nodeset = Nokogiri::HTML.parse(get.response.toutf8.scrub('')) nodeset.search('script').remove nodeset.css('body').each do |node| text = node.content.gsub(/(\s)/, '') begin @@mecab.parse(text) do |n| next unless n.feature.match('名詞') word = n.surface @word_frequency[word.scrub('')] = 1 if !word.nil? && word.length.between?(2, 10) end rescue Natto::MeCabError => e end end end end end def recommend_books words = params[:words] @word_books = [] if words.nil? render nothing: true, status: 400 and return end words.each do |word| books = Book.search(word) @word_books << [word, books] end end def answer book_id = params[:book_id] selection = params[:selection] if book_id.nil? || selection.nil? render nothing: true, status: 400 and return end answer = Answer.new(book_id: book_id, selection: selection) if answer.save render nothing: true, status: 200 else render nothing: true, status: 400 end end def help end end
require 'rimac' module Chillon class Handler def initialize(token) @access = Rimac::API.new(token) end def process(parser) if parser.multiple_results? results = Hash.new parser.guids.map do |guid| results[guid] = get_from_access(guid) end results else get_from_access(parser.guid) end end def get_from_access(guid) @access.get(guid) end end end
class Bakery < ActiveRecord::Base has_many :baked_goods end
require 'rails_helper' RSpec.feature "Static", type: :feature do context 'view index page' do scenario 'should be successful' do visit root_path expect(page).to have_content('A simple list application') end end context 'view about page' do scenario 'should be successful' do visit about_path expect(page).to have_content('About List-It') end end end
require 'test_helper' class StockAuditsControllerTest < ActionController::TestCase setup do @stock_audit = stock_audits(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:stock_audits) end test "should get new" do get :new assert_response :success end test "should create stock_audit" do assert_difference('StockAudit.count') do post :create, stock_audit: { alternator: @stock_audit.alternator, comment: @stock_audit.comment, engine: @stock_audit.engine, stock: @stock_audit.stock, user: @stock_audit.user } end assert_redirected_to stock_audit_path(assigns(:stock_audit)) end test "should show stock_audit" do get :show, id: @stock_audit assert_response :success end test "should get edit" do get :edit, id: @stock_audit assert_response :success end test "should update stock_audit" do patch :update, id: @stock_audit, stock_audit: { alternator: @stock_audit.alternator, comment: @stock_audit.comment, engine: @stock_audit.engine, stock: @stock_audit.stock, user: @stock_audit.user } assert_redirected_to stock_audit_path(assigns(:stock_audit)) end test "should destroy stock_audit" do assert_difference('StockAudit.count', -1) do delete :destroy, id: @stock_audit end assert_redirected_to stock_audits_path end end
# The game is a large case statement with child case statements within it. I wanted to create a story/path for the player to follow. # At this time, since I have many different deaths to track, I stayed away from using variables for deaths. # I tailored each death out to the path the player chose. # In the future, I look forward to thinking about ways to make this code less repetitive. # Before the code for the game begins, I've added variables for my game title, win, and game over message. game_over_text = " ▄████ ▄▄▄ ███▄ ▄███▓▓█████ ▒█████ ██▒ █▓▓█████ ██▀███ ██▒ ▀█▒▒████▄ ▓██▒▀█▀ ██▒▓█ ▀ ▒██▒ ██▒▓██░ █▒▓█ ▀ ▓██ ▒ ██▒ ▒██░▄▄▄░▒██ ▀█▄ ▓██ ▓██░▒███ ▒██░ ██▒ ▓██ █▒░▒███ ▓██ ░▄█ ▒ ░▓█ ██▓░██▄▄▄▄██ ▒██ ▒██ ▒▓█ ▄ ▒██ ██░ ▒██ █░░▒▓█ ▄ ▒██▀▀█▄ ░▒▓███▀▒ ▓█ ▓██▒▒██▒ ░██▒░▒████▒ ░ ████▓▒░ ▒▀█░ ░▒████▒░██▓ ▒██▒ ░▒ ▒ ▒▒ ▓▒█░░ ▒░ ░ ░░░ ▒░ ░ ░ ▒░▒░▒░ ░ ▐░ ░░ ▒░ ░░ ▒▓ ░▒▓░ ░ ░ ▒ ▒▒ ░░ ░ ░ ░ ░ ░ ░ ▒ ▒░ ░ ░░ ░ ░ ░ ░▒ ░ ▒░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ " game_win_text = " ▓██ ██▓ ▒█████ █ ██ █ █░ ██▓ ███▄ █ ▐██▌ ▒██ ██▒▒██▒ ██▒ ██ ▓██▒ ▓█░ █ ░█░▓██▒ ██ ▀█ █ ▐██▌ ▒██ ██░▒██░ ██▒▓██ ▒██░ ▒█░ █ ░█ ▒██▒▓██ ▀█ ██▒ ▐██▌ ░ ▐██▓░▒██ ██░▓▓█ ░██░ ░█░ █ ░█ ░██░▓██▒ ▐▌██▒ ▓██▒ ░ ██▒▓░░ ████▓▒░▒▒█████▓ ░░██▒██▓ ░██░▒██░ ▓██░ ▒▄▄ ██▒▒▒ ░ ▒░▒░▒░ ░▒▓▒ ▒ ▒ ░ ▓░▒ ▒ ░▓ ░ ▒░ ▒ ▒ ░▀▀▒ ▓██ ░▒░ ░ ▒ ▒░ ░░▒░ ░ ░ ▒ ░ ░ ▒ ░░ ░░ ░ ▒░ ░ ░ ▒ ▒ ░░ ░ ░ ░ ▒ ░░░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ " game_title = " ▓█████ ██████ ▄████▄ ▄▄▄ ██▓███ ▓█████ ▓█ ▀ ▒██ ▒ ▒██▀ ▀█ ▒████▄ ▓██░ ██▒▓█ ▀ ▒███ ░ ▓██▄ ▒▓█ ▄ ▒██ ▀█▄ ▓██░ ██▓▒▒███ ▒▓█ ▄ ▒ ██▒▒▓▓▄ ▄██▒░██▄▄▄▄██ ▒██▄█▓▒ ▒▒▓█ ▄ ░▒████▒▒██████▒▒▒ ▓███▀ ░ ▓█ ▓██▒▒██▒ ░ ░░▒████▒ ░░ ▒░ ░▒ ▒▓▒ ▒ ░░ ░▒ ▒ ░ ▒▒ ▓▒█░▒▓▒░ ░ ░░░ ▒░ ░ ░ ░ ░░ ░▒ ░ ░ ░ ▒ ▒ ▒▒ ░░▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ " game_title_img= " .o oOOOOOOOo OOOo Ob.OOOOOOOo OOOo. oOOo. .adOOOOOOO OboO00000000000.OOo. .oOOOOOo. OOOo.oOOOOOo..0000000000OO OOP.oOOOOOOOOOOO 0POOOOOOOOOOOo. 00OOOOOOOOOP,OOOOOOOOOOOB0 0O0OOOO0 0OOOOo0OOOOOOOOOOO0 .adOOOOOOOOO0oOOO0 0OOOOo oOOOO0 0OOOOOOOOOOOOOOOOOOOOOOOOOO' oOO OOOOO ooOOOOOOOOOOOOOOOOoo oOO oOOOOOba. .adOOOOOOOOOOba .adOOOOo. oOOOOOOOOOOOOOba. .adOOOOOOOOOO@^OOOOOOOba. .adOOOOOOOOOOOO OOOOOOOOOOOOOOOOO.OOOOOOOOOOOOOOoo ooOOOOOOOOOOOOO.OOOOOOOOOOOOOO oOOOO0 oYOoOOOOMOIONODOOoo . ooOOROAOPOEOOOoOYo oOOOo Y oOOOOOOOOOOOOOO: .oOOo. :OOOOOOOOOOO?o :o : .oO00OOOOOOOOOo.OOOOOO.oOOOOOOOOOOOO? . . oOOP00OOOOOOOOoOOOOOOOooOOOOO?OOOO?OOo ooo OOOOOOOOoo?OOOOO?OOOOOOpOOO?o ?$o oOOOO? oOoY o ?OOOOo o . . . OPo : o . . " # Setting up my typing speed with a proc! Changing the speed around and testing things really saves time with this. # I used the .each_char method to print out my characters one by one. Like in an old style game. type_speed = Proc.new { |chars| print chars; sleep 0.02; $stdout.flush } ## let the game begin! puts game_title puts game_title_img puts "\n" puts " Type the commands in the square brackets to play!" puts " To exit, hit Ctrl+C. Stay Alive." puts " Difficulty Level: Nightmare" puts " Only two ways to survive." puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" sleep(2) "You wake up in a dark and dirty room with a horrible headache.\n".each_char(&type_speed) "What happened? \nWhere the hell are you? \nWhat should you do? \n".each_char(&type_speed) puts "\n" sleep(1) puts "Should you:" puts "[Exit] Exit the room. You're getting out of this dump." puts "[Look] Look out the window. Maybe you can see where you are." # I named my questions with names such as quest_rm_ex or quest_rm_lk, so I can see what path the player is one. quest_rm = gets.chomp.downcase case quest_rm # Tree_name: rm_ex. For easier reading, before you open this, close the other trees. when "exit" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You walk outside. It's cold. You shiver in the dark hallway and see a dim light at the end of it.\n".each_char(&type_speed) sleep (1) puts "\n" puts "Should you:" puts "[Walk] Walk to the light. Maybe it's warmer there." puts "[Turn] Turn away from the light and walk in the opposite direction." quest_rm_ex = gets.chomp.downcase case quest_rm_ex when "walk" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "The dim light leads to a grimy kitchen. The light is the kitchen hood shining over the stove top.\n".each_char(&type_speed) "You hear footsteps behind you coming from the hallway.\n".each_char(&type_speed) sleep(1) puts "\n" puts "Should you:" puts "[Off] Turn off the light switch. It'll be easier to hide that way." puts "[Escape] Quick run! Avoid the footsteps!" quest_rm_ex_wk = gets.chomp.downcase case quest_rm_ex_wk when "off" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You switch off the lights. Unfortunately, you can't see where you are now.\n".each_char(&type_speed) "Suddenly, you feel a sharp pain at the back of your head, and blood oozing down your neck.\n".each_char(&type_speed) "You drop to the ground as everything fades to black...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text when "escape" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You run to the other side of the kitchen. You were hoping to find an exit, but there is no way out.\n".each_char(&type_speed) "You turn and find yourself face to face with a muscular and brute figure whose long hair covers their face.\n".each_char(&type_speed) "You try to fight back, but everything fades to black as you are overpowered...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text else puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You hear footsteps behind you. Suddenly, you feel a sharp pain \nat the back of your head, and blood oozing down your neck.\n".each_char(&type_speed) "You drop to the ground as everything fades to black...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text end when "turn" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You walk away from the dim light and turn to go the other direction. \n".each_char(&type_speed) "At the end of the hallway you find stairs. \nOnce downstairs, you find a door that leads outside.\n".each_char(&type_speed) "The area is secluded. There aren't any other houses close by.\n".each_char(&type_speed) sleep(1) puts "\n" puts "Should you:" puts "[Road] Go to the dirt road." puts "[Forest] Go to the forest." quest_rm_ex_tn = gets.chomp.downcase case quest_rm_ex_tn when "road" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You run toward the dirt road. You follow it for some time, and end up on a larger country road.\n".each_char(&type_speed) "You see two headlights far away in the distance.\nYou run to the center of the street and wave your arms for help.\n".each_char(&type_speed) "You hear a roar from the dirt road where you came from. \nYou see the monster making its way toward you.\n".each_char(&type_speed) "You start to run toward the two headlights, but the monster is close behind.\n".each_char(&type_speed) "The headlights are getting closer, but you're afraid it might be too late.".each_char(&type_speed) puts "\n" puts "\n" "It's right behind you.".each_char(&type_speed) puts "\n" puts "\n" "Just when you think you'll be caught, the car hits it. It's gone. \nThe driver runs to you to see how you are doing.\n".each_char(&type_speed) "You both drive away as soon as possible. You don't bother to find out what the hell that monster was.".each_char(&type_speed) sleep(1) puts "\n" puts game_win_text when "forest" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You run toward the line of trees and end up in the forest. \nYou were hoping to find a better place to hide, but instead you are lost.\n".each_char(&type_speed) "You turn and find yourself face to face with a muscular and brute figure whose long hair covers their face.\n".each_char(&type_speed) "You try to fight back, but everything fades to black as you are overpowered...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text else puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You hear footsteps behind you. Suddenly, you feel a sharp pain \nat the back of your head, and blood oozing down your neck.\n".each_char(&type_speed) "You drop to the ground as everything fades to black...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text end else puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You hear footsteps behind you. Suddenly, you feel a sharp pain \nat the back of your head, and blood oozing down your neck.\n".each_char(&type_speed) "You drop to the ground as everything fades to black...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text end # Tree name: rm_lk. For easier reading, before you open this, close the other trees. when "look" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "Where the hell are you? You look out the window and see only a large \nbarren backyard followed by a line of trees and forest.\n".each_char(&type_speed) "The trees continue on for miles. \nSuddenly, you hear the door knob rattle and shake.\n".each_char(&type_speed) sleep (1) puts "\n" puts "Should you:" puts "[Hold] Hold the door knob and block the door with your body." puts "[Confront] You see a bat on the floor. Pick it up and defend yourself." quest_rm_lk = gets.chomp.downcase case quest_rm_lk when "hold" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You hold the door and push your body against it. \nYou don't want anyone entering right now\n".each_char(&type_speed) "The person on the other side is banging on the door. \nSuddenly, they hit the door with a crowbar.\n".each_char(&type_speed) "They keep on hitting the door without stopping, \nthe hole is almost large enough for them to come inside.\n".each_char(&type_speed) sleep(1) puts "\n" puts "Should you:" puts "[Escape] You see a window across the room. Escape through there." puts "[Confront] You see a bat on the floor. Pick it up and defend yourself." quest_rm_lk_hl = gets.chomp.downcase case quest_rm_lk_hl when "escape" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You decide to escape by jumping out the window. \nYou realize too late that you are on the third floor of a house. \n".each_char(&type_speed) "You meet your end when you hit the ground.\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text when "confront" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "The door bursts opens and a figure storming into the room charges at you with a crowbar.\n".each_char(&type_speed) "Thankfully you grabbed that bat off the floor. You dodge a few swings and hit him across the head.\n".each_char(&type_speed) puts "\n" "It's knocked out.\n".each_char(&type_speed) puts "\n" "You run out of the room as fast as you can.\nYou find a phone in the kitchen and call the police.\n".each_char(&type_speed) "You don't wait for them to arrive with that thing in the house.\nYou run to the road outside and wait for them there.\n".each_char(&type_speed) "You don't bother to find out what the hell that monster was. You just want to go home as fast as possible.".each_char(&type_speed) sleep(1) puts "\n" puts game_win_text else puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "The door bursts opens and a figure storming into the room hits you with the crowbar.\n".each_char(&type_speed) "You try to fight back, but everything fades to black as you are overpowered...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text end when "confront" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "The door bursts opens and a figure storming into the room charges at you with a crowbar.\n".each_char(&type_speed) "Thankfully you grabbed that bat off the floor. You dodge a few swings and hit him across the head.\n".each_char(&type_speed) "He falls to the ground. Is he knocked out?\n".each_char(&type_speed) sleep(1) puts "\n" puts "Should you:" puts "[Look] Look more closely at who the hell this. Why were they trying to hit you with a crowbar?" puts "[Hit] Hit them again with the bat for good measure. Make sure this thing doesn't wake up again." quest_rm_lk_cn = gets.chomp.downcase case quest_rm_lk_cn when "look" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You take a closer look at who this is. Why are they trying to hurt you? \n".each_char(&type_speed) "You have no time to figure out as they wake up again and bring you down to the ground.\n".each_char(&type_speed) "You try to fight back, but everything fades to black as you are overpowered...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text when "hit" puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You hit them again across the head. You want to make sure \nthey are really knocked out. You aren't taking any chances.\n".each_char(&type_speed) "Suddenly the figure wakes up again, unharmed, and drags you down to the ground.\n".each_char(&type_speed) "You try to fight back but everything fades to black as you are overpowered...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text else puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "You were able to beat down this weirdo who tried to hurt you.\nYou walk away from them and exit the room.\n".each_char(&type_speed) "You hear footsteps behind you. Suddenly, you feel a sharp pain \nat the back of your head, and blood oozing down your neck.\n".each_char(&type_speed) "You drop to the ground as everything fades to black...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text end else puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "The door bursts opens and a figure storming into the room hits you with a crowbar.\n".each_char(&type_speed) "You try to fight back, but everything fades to black as you are overpowered...\n".each_char(&type_speed) sleep(1) puts "\n" puts game_over_text end # For those who don't want to follow the rules! else puts "\n" puts "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" puts "\n" "The door bursts opens and a figure storming into the room hits you with a crowbar.\n".each_char(&type_speed) "Everything fades to black as you lay on the bed...\n".each_char(&type_speed) sleep (1) puts game_over_text end
Given 'the config file:' do |body| CommandLineHelpers.set_config_file body end Given 'the mustache:' do |body| CommandLineHelpers.set_mustache_file body end When "I ride the mustache with '$args'" do |args| @last_invocation = CommandLineHelpers.invoke_mustache_file_with args end Then 'I see:' do |output| @last_invocation.stdout.should include strip_leading(output) end Then /^(stdout|stderr) is empty$/ do |stream_name| @last_invocation.send(stream_name).should == '' end Then 'the exit status is $status' do |status| @last_invocation.exitstatus.to_s.should == status end
Sequel.migration do up do alter_table(:users_seasons_matches) do add_column :game_wins, Integer, :null => false, :default => 0 end alter_table(:matches) do add_column :best_of, Integer, :null => false, :default => 3 end end down do alter_table(:users_seasons_matches) do drop_column :game_wins end alter_table(:matches) do drop_column :best_of end end end
require "pry" require "sinatra/base" require "sinatra/json" require "./db/setup" require "./lib/all" require "rack/cors" require "httparty" require "uri" class Plock < Sinatra::Base set :logging, true set :show_exceptions, false use Rack::Cors do allow do origins "*" resource "*", headers: :any, methods: :any end end error do |e| if e.is_a? ActiveRecord::RecordNotFound halt 404 elsif e.is_a? ActiveRecord::RecordInvalid json error: e.message elsif e.is_a? ActiveRecord::RecordNotUnique halt 400 json error: e.message else puts e.message end end def user name, password User.find_by(username: name, password: password) end #---------------------------------------------------------------- get "/my_bookmarks" do u = user params[:username], params[:password] if u status 200 body json u.bookmarks else status 400 halt({ error: "User not found" }.to_json) end end post "/my_bookmarks" do u = user params[:username], params[:password] if params[:bookmark_url] =~ /\A#{URI::regexp(['http', 'https'])}\z/ u.bookmarks.create!( user_id: params[:user_id], bookmark_url: params[:bookmark_url], bookmark_name: params[:bookmark_name], bookmark_description: params[:bookmark_description] ) status 200 json u.bookmarks else status 422 halt({error: "That is not a valid URL (Please include the 'http' section)"}.to_json) end end get "/recommendations" do u = user params[:username], params[:password] hash = [] if u u.recommendations.each do |b| hash.push(b.bookmark) end status 200 body json hash else status 400 halt({ error: "User not found" }.to_json) end end post "/recommendations" do recommendation = params[:bookmark_id].to_i bookmark = Bookmark.find_by(id: recommendation) recipient = params[:recipient] r = User.find_by(username: recipient) u = user params[:username], params[:password] sender = u.username if u nr = Recommendation.create!(user_id: u.id, recipient_id: r.id, bookmark_id: bookmark.id) sender = u.username data = { channel: "#plock_recommendations", username: "Plock!", text: "@#{sender} recommended a link to @#{r.username}! View it <#{bookmark.bookmark_url}|here!> ", icon_emoji: ":aardwolf2:", link_names: 2 } HTTParty.post "https://hooks.slack.com/services/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", body: { payload: data.to_json } status 200 body json r.recommendations else status 400 halt({error: "User not found"}.to_json) end end post "/:id/my_bookmarks" do u = user params[:username], params[:password] # if u deleting_item = u.bookmarks.find_by(:id) deleting_item.delete status 200 # else status 404 halt({ error: "Can not delete bookmark" }.to_json) # end end end if $PROGRAM_NAME == __FILE__ Plock.run! end
# frozen_string_literal: true require_relative "vm_translator/version" require_relative "vm_translator/lexer" require_relative "vm_translator/parser" require_relative "vm_translator/compiler" require_relative "vm_translator/commands/push" require_relative "vm_translator/commands/pop" require_relative "vm_translator/commands/add" require_relative "vm_translator/commands/sub" require_relative "vm_translator/commands/and" require_relative "vm_translator/commands/or" require_relative "vm_translator/commands/not" require_relative "vm_translator/commands/neg" require_relative "vm_translator/commands/eq" require_relative "vm_translator/commands/lt" require_relative "vm_translator/commands/gt" require_relative "vm_translator/commands/label_definition" require_relative "vm_translator/commands/goto" require_relative "vm_translator/commands/if_goto" require_relative "vm_translator/commands/return" require_relative "vm_translator/commands/function" require_relative "vm_translator/commands/call" require_relative "vm_translator/commands/bootstrap" require "pry-byebug" module VmTranslator class Error < StandardError; end # Your code goes here... def self.translate(vm_program_directory) bootstrap_code = Compiler.new("Sys").compile([Commands::Bootstrap.new]) compiled_files = Dir[vm_program_directory + "/*.vm"].map do |vm_file_path| expanded_vm_file_path = File.expand_path(vm_file_path) lexer = Lexer.new(File.read(expanded_vm_file_path)) parser = Parser.new(lexer.tokens) vm_file_name = File.basename(vm_file_path, ".vm") Compiler.new(vm_file_name).compile(parser.commands) end compiled_assembly = ([bootstrap_code] + compiled_files).join asm_file_name = File.basename(vm_program_directory) + ".asm" File.write("#{vm_program_directory}/#{asm_file_name}", compiled_assembly) end end
require 'spec_helper' describe SaldoBancarioHistorico do before do @user = Factory(:user) @fecha = "25/09/2012 23:06" @saldo = Factory(:saldo_bancario, :user => @user, :updated_at => @fecha) @attr = {:user_id => @user.id, :saldo_bancario => @saldo, :valor => @saldo.valor_cents, :valor_currency => @saldo.valor_currency, :fecha_de_alta => @saldo.updated_at} end describe "exitoso" do it "debe guardarse correctamente" do SaldoBancarioHistorico.create!(@attr) end describe "asociaciones" do before do @sbh = SaldoBancarioHistorico.create!(@attr) end it "should have a user attribute" do @sbh.should respond_to(:user) end it "should have a saldo_bancario attribute" do @sbh.should respond_to(:saldo_bancario) end it "should have a fecha_de_alta attribute" do @sbh.should respond_to(:fecha_de_alta) end it "should have a valor attribute" do @sbh.should respond_to(:valor) end it "should have a valor_cents attribute" do @sbh.should respond_to(:valor_cents) end it "should have a valor_currency attribute" do @sbh.should respond_to(:valor_currency) end it "should have the right associated user" do @sbh.user_id.should == @user.id @sbh.user.should == @user end it "valor es del tipo money" do @sbh.valor == Money.new(@attr[:valor], @attr[:valor_currency]) end end end describe "fallido" do it "el usuario no debe ser nulo" do SaldoBancarioHistorico.new(@attr.merge(:user_id => nil)).should_not be_valid end it "el saldo bancario no debe ser nulo" do SaldoBancarioHistorico.new(@attr.merge(:saldo_bancario => nil)).should_not be_valid end it "el valor del saldo bancario no debe ser nulo" do SaldoBancarioHistorico.new(@attr.merge(:valor => nil)).should_not be_valid end it "el valor del saldo bancario no debe ser vacio" do SaldoBancarioHistorico.new(@attr.merge(:valor => "")).should_not be_valid end it "el valor del saldo bancario no debe ser nulo" do SaldoBancarioHistorico.new(@attr.merge(:valor_cents => nil)).should_not be_valid end it "el valor del saldo bancario no debe ser vacio" do SaldoBancarioHistorico.new(@attr.merge(:valor_cents => "")).should_not be_valid end it "la moneda del saldo bancario no debe ser nula" do SaldoBancarioHistorico.new(@attr.merge(:valor_currency => nil)).should_not be_valid end it "la moneda del saldo bancario no debe ser vacia" do SaldoBancarioHistorico.new(@attr.merge(:valor_currency => "")).should_not be_valid end it "la fecha de alta del saldo bancario no debe ser nula" do SaldoBancarioHistorico.new(@attr.merge(:fecha_de_alta => nil)).should_not be_valid end it "la fecha de alta del saldo bancario no debe ser vacia" do SaldoBancarioHistorico.new(@attr.merge(:fecha_de_alta => "")).should_not be_valid end end end
#-- # FIXME: # # Should use permalink. # If permalinks can cross instances, URI must be scoped. #++ # This resource represents an ArticleCategory within the system. It contains # all of the properties and associations of an ArticleCategory. # # ArticleCategory resources are exclusive to Article resources. See # ProductCategory for a description of the resource that organizes Product, # Review, and some Forum resources. # # [UUID] The unique identifier for an ArticleCategory resource is the # ArticleCategory's internal ID number. # # [URI] <tt>/resources/article_categories/{article_category-uuid}</tt> class Restful::ArticleCategory < Restful::Resource::Base ## # :method: Version(1) # # # ==== Examples # # JSON: # # { # "parent":null, # "page_title":"Holiday Blog", # "short_name":null, # "updated_at":"2010-02-05T12:38:21-06:00", # "display_title":"Holiday", # "created_at":"2009-12-17T23:49:27-06:00", # "href":"/resources/article_categories/1", # "children":"/resources/article_categories/1/children{?limit,offset,order}", # "display_order":23, # "partner_key":null # } # # # XML: # # <article-category> # <parent nil="true"></parent> # <page-title>Holiday Blog</page-title> # <short-name nil="true"></short-name> # <updated-at type="datetime">2010-02-05T12:38:21-06:00</updated-at> # <display-title>Holiday</display-text> # <created-at type="datetime">2009-12-17T23:49:27-06:00</created-at> # <href>/resources/article_categories/1</href> # <children>/resources/article_categories/1/children{?limit,offset,order}</children> # <display-order type="integer">23</display-order> # <partner-key nil="true"></partner-key> # </article-category> version 1 ## # :method: href # # A self-referencing *link* to the ArticleCategory resource. # # Return Type:: ArticleCategory # Protected?:: No link ## # A reference to the parent ArticleCategory for this ArticleCategory. Not # all ArticleCategories will have a parent. # # Return Type:: ArticleCategory # Protected?:: No link :parent ## # References a paginated list of child ArticleCategories in which # this ArticleCategory is a parent. # # Return Type:: ArticleCategory # Protected?:: No link :children #-- # TODO: # link :articles #++ ## # The suggested ordering of this ArticleCategory (within the scope of its # parent). # # Return Type:: Integer # Protected?:: No attribute :display_order ## # The page title for this ArticleCategory. # # Return Type:: String # Protected?:: No attribute :page_title ## # The display title for this ArticleCategory. # # Return Type:: String # Protected?:: No attribute :display_title, :display_text ## # A shorter title for this ArticleCategory, can be null. # # Return Type:: String # Protected?:: No attribute :short_name ## # A key, provided by the partner site, used to identify this ArticleCategory. # This can be null. # # Return Type:: String # Protected?:: No #-- # FIXME: Should this be private? #++ attribute :partner_key ## # :method: created_at # # The date and time this ArticleCategory was created. # # Return Type:: Datetime # Protected?:: No ## # :method: updated_at # # The date and time this ArticleCategory was last updated. # # Return Type:: Datetime # Protected?:: No timestamps end
class ChangeDataTypeMasterContactsId < ActiveRecord::Migration def up change_column :purchase_contacts, :master_contact_ids, :text end def down change_column :purchase_contacts, :master_contact_ids, :varchar end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :phone do association :contact phone {"123-555-1234"} phone_type 'home' end end
class ServiceCategory < ApplicationRecord has_many :services, through: :service_sub_categories end
class Group < ActiveRecord::Base validates :name, presence: true, length: {maximum: 20}, uniqueness: true has_many :user_groups has_many :users, :through => :user_groups end
class CreateTaxes < ActiveRecord::Migration def change create_table :taxes do |t| t.string :full_name t.string :reference t.string :ic_new t.string :ic_old t.boolean :citizen_of_malaysia t.string :sex t.string :marital_status t.date :marital_date t.string :type_of_assessment t.boolean :general_resolutions_complied t.string :address1 t.string :address2 t.string :postcode t.string :city t.string :state t.string :phone t.string :employer_reference_number t.string :email t.string :bank_name t.string :bank_account_number t.string :spouse_full_name t.string :spouse_reference_number t.string :spouse_ic_new t.string :spouse_ic_old t.integer :C1 t.integer :C2 t.integer :C3 t.integer :C4 t.integer :C5 t.integer :C6 t.integer :C7 t.integer :C8 t.integer :C8A t.integer :C9 t.integer :C10 t.integer :C11 t.integer :C12 t.integer :C13 t.integer :C14 t.integer :C15 t.integer :C16 t.integer :C17 t.integer :C18 t.integer :D1 t.integer :D2 t.integer :D3 t.integer :D4 t.integer :D5 t.integer :D6 t.integer :D7 t.integer :D8 t.integer :D8A t.integer :D8B t.integer :D8C t.integer :D8D t.integer :D9 t.integer :D10 t.integer :D11 t.integer :D11A t.integer :D11B t.integer :D11C t.integer :D12 t.integer :D13 t.integer :D14 t.integer :E1 t.integer :E2 t.integer :E2A t.integer :E2B t.integer :E3 t.integer :E4 t.integer :E5 t.integer :E6 t.integer :E7 t.integer :E8 t.integer :E9 t.integer :E10 t.integer :E11 t.integer :E12 t.integer :E13 t.integer :E14 t.integer :E15 t.integer :F1 t.integer :F2 t.integer :F3 t.integer :F4 t.timestamps end end end
class ExpensesController < ApplicationController def index respond_to do |format| format.html format.json { @expenses = Datatable.new(params, ExpensesSearch.new) } end end def approve change_expense_status("Approved") end def reject change_expense_status("Rejected") end def pend change_expense_status("Pending") end private def find_expense @expense = Expense.find(params[:id]) end def change_expense_status(new_status) find_expense @expense.update!(status: new_status) render "update_status" end end
class Snapchat attr_accessor :username, :snap_story, :memories def initiative(user) @user = user end def snap
FactoryGirl.define do factory :user do fullname "MyString" email "MyString" password "MyString" end end # t.string :domain # t.string :fullname # t.string :email # t.string :password_digest
class Comment < ActiveRecord::Base belongs_to :user belongs_to :finstagram_post has_many :comment_likes validates_presence_of :text, :user, :finstagram_post end def like_count self.likes.size end
require 'rails_helper' RSpec.configure do |config| config.swagger_root = Rails.root.to_s + '/swagger' config.swagger_docs = { 'v1/swagger.json' => { openapi: '3.0.1', info: { title: 'API V1', version: 'v1', description: 'This is the first version of my API' }, servers: [ { url: 'https://{defaultHost}', variables: { defaultHost: { default: 'www.example.com' } } } ] } } end
require 'set' # @param {Character[][]} board # @return {Boolean} def is_valid_sudoku(board) #check 3 x 3 squares for row_start in (0..6).step(3) do for col_start in (0..6).step(3) do set = Set.new for i in (0..2) do for j in (0..2) do cur_val = board[i+row_start][j+col_start] next if cur_val == "." return false if set.include? cur_val set.add cur_val end end end end # check rows for row in (0..8) do set = Set.new for col in (0..8) do cur_val = board[row][col] next if cur_val == "." return false if set.include? cur_val set.add cur_val end end # check columns for col in (0..8) do set = Set.new for row in (0..8) do cur_val = board[row][col] next if cur_val == "." return false if set.include? cur_val set.add cur_val end end true end valid = [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] invalid = [ ["8","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9",".",".",".",".",".","6","."], [".",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] p is_valid_sudoku valid p is_valid_sudoku invalid
class ReviewsController < ApplicationController before_action :authenticate_user! before_action :find_products def new @review = Review.new end def create @review = Review.new(review_params) @review.user_id = current_user.id @review.product_id = @product.id if @review.save redirect_to @product else flash[:warning] = "评论没有内容哦!" redirect_to @product end end private def review_params params.require(:review).permit(:comment) end def find_products @product = Product.find(params[:product_id]) end end
class AddPlayersCountToMatches < ActiveRecord::Migration def change add_column :matches, :players_count, :integer, default: 0, null: false, after: :started_at end end
class CreateFollows < ActiveRecord::Migration[5.2] def change create_table :follows do |t| t.integer :follower_id t.integer :followed_id t.index [:follower_id, :followed_id], unique: true end end end
class JoinTableEleSimulationContract < ApplicationRecord belongs_to :ele_simulation belongs_to :ele_contract end
# == Schema Information # # Table name: virtual_tourisms # # id :integer not null, primary key # title :string(255) # description :string(255) # created_at :datetime not null # updated_at :datetime not null # video_file_name :string(255) # video_content_type :string(255) # video_file_size :integer # video_updated_at :datetime # video_url :string(255) # thumb_nail_file_name :string(255) # thumb_nail_content_type :string(255) # thumb_nail_file_size :integer # thumb_nail_updated_at :datetime # class VirtualTourism < ActiveRecord::Base has_attached_file :thumb_nail, styles: { small: "300x400>"}, processors: [:thumbnail, :compression] validates_attachment :thumb_nail, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png"] } # has_attached_file :video # validates_attachment_content_type :video, content_type: /\Avideo\/.*\Z/ # validates_presence_of :video # def video_thumb # self.video.try(:url).try(:gsub, /\/original\//, '/thumb/').try(:gsub, /(\.[a-z|A-Z]*$)/, '.jpg') # end end
require 'httparty' require 'apicake' require 'json' require 'ostruct' class Newsapi < APICake::Base base_uri 'https://newsapi.org' attr_reader :api_key, :last_payload, :parsed_response def initialize(api_key) @api_key = api_key end def default_query { apiKey: @api_key } end def self.top_headlines napi = Newsapi.new '8be3133fee004afe9866824a491f4e83' napi.v2 'top-headlines', langauge: 'en', country: 'us', category: 'science' #, #apiKey: '8be3133fee004afe9866824a491f4e83' results = napi.last_payload Results.new(results) end class Result < OpenStruct end class Results def initialize(results) results.map.each {|r| Result.new(r) } end end end # #Everything.new(:q, :qInTitle, :sources, :domains, :excludedDomains, :from, :to, :language, :sortBy, :pageSize, :page) #Sources.new(:category, :language, :country) # # #napi = Napi::Newsapi.new '8be3133fee004afe9866824a491f4e83' # # #napi.v2 'top-headlines', country: 'us', category: 'category', sources: 'sources', q: 'q', pageSize: 'pageSize', page: 'page' # #napi.v2 'everything', q: 'q', qInTitle: 'qInTitle', sources: 'sources', domains: 'domains', excludedDomains: 'excludedDomains', from: 'from', to: 'to', language: 'language', sortBy: 'sortBy', pageSize: #'pageSize', page: 'page' # #napi.v2 'sources', category: 'category', language: 'language', country: 'country' # # # #
class CreateSongs < ActiveRecord::Migration def up create_table :songs do |s| s.string :name s.text :description end end def down drop_table :songs end end
class BoardController < ApplicationController layout 'board' def index @people = Person.all end end
require "identity_robotargeter/engine" module IdentityRobotargeter SYSTEM_NAME = 'robotargeter' SYNCING = 'campaign' CONTACT_TYPE = 'call' ACTIVE_STATUS = 'active' FINALISED_STATUS = 'finalised' FAILED_STATUS = 'failed' PULL_JOBS = [[:fetch_new_calls, 30.minutes], [:fetch_new_redirects, 30.minutes], [:fetch_active_campaigns, 30.minutes]] MEMBER_RECORD_DATA_TYPE='object' def self.push(sync_id, member_ids, external_system_params) begin campaign_id = JSON.parse(external_system_params)['campaign_id'].to_i phone_type = JSON.parse(external_system_params)['phone_type'].to_s priority = ApplicationHelper.integer_or_nil(JSON.parse(external_system_params)['priority']) || 1 campaign_name = Campaign.find(campaign_id).name audience = Audience.create!(sync_id: sync_id, campaign_id: campaign_id, priority: priority) members = Member.where(id: member_ids).with_phone_type(phone_type) yield members, campaign_name rescue => e audience.update_attributes!(status: FAILED_STATUS) if audience raise e end end def self.push_in_batches(sync_id, members, external_system_params) begin audience = Audience.find_by_sync_id(sync_id) audience.update_attributes!(status: ACTIVE_STATUS) campaign_id = JSON.parse(external_system_params)['campaign_id'].to_i phone_type = JSON.parse(external_system_params)['phone_type'].to_s members.in_batches(of: Settings.robotargeter.push_batch_amount).each_with_index do |batch_members, batch_index| rows = ActiveModel::Serializer::CollectionSerializer.new( batch_members, serializer: RobotargeterMemberSyncPushSerializer, audience_id: audience.id, campaign_id: campaign_id, phone_type: phone_type ).as_json write_result_count = Callee.add_members(rows) yield batch_index, write_result_count end audience.update_attributes!(status: FINALISED_STATUS) rescue => e audience.update_attributes!(status: FAILED_STATUS) raise e end end def self.description(sync_type, external_system_params, contact_campaign_name) external_system_params_hash = JSON.parse(external_system_params) if sync_type === 'push' "#{SYSTEM_NAME.titleize} - #{SYNCING.titleize}: #{contact_campaign_name} ##{external_system_params_hash['campaign_id']} (#{CONTACT_TYPE})" else "#{SYSTEM_NAME.titleize}: #{external_system_params_hash['pull_job']}" end end def self.base_campaign_url(campaign_id) Settings.robotargeter.base_campaign_url ? sprintf(Settings.robotargeter.base_campaign_url, campaign_id.to_s) : nil end def self.worker_currenly_running?(method_name) workers = Sidekiq::Workers.new workers.each do |_process_id, _thread_id, work| matched_process = work["payload"]["args"] = [SYSTEM_NAME, method_name] if matched_process puts ">>> #{SYSTEM_NAME.titleize} #{method_name} skipping as worker already running ..." return true end end puts ">>> #{SYSTEM_NAME.titleize} #{method_name} running ..." return false end def self.get_pull_jobs defined?(PULL_JOBS) && PULL_JOBS.is_a?(Array) ? PULL_JOBS : [] end def self.get_push_jobs defined?(PUSH_JOBS) && PUSH_JOBS.is_a?(Array) ? PUSH_JOBS : [] end def self.pull(sync_id, external_system_params) begin pull_job = JSON.parse(external_system_params)['pull_job'].to_s self.send(pull_job, sync_id) do |records_for_import_count, records_for_import, records_for_import_scope, pull_deferred| yield records_for_import_count, records_for_import, records_for_import_scope, pull_deferred end rescue => e raise e end end def self.fetch_new_calls(sync_id, force: false) ## Do not run method if another worker is currently processing this method yield 0, {}, {}, true if self.worker_currenly_running?(__method__.to_s) started_at = DateTime.now last_updated_at = Time.parse($redis.with { |r| r.get 'robotargeter:calls:last_updated_at' } || '1970-01-01 00:00:00') updated_calls = Call.updated_calls(force ? DateTime.new() : last_updated_at) updated_calls_all = Call.updated_calls_all(force ? DateTime.new() : last_updated_at) iteration_method = force ? :find_each : :each updated_calls.send(iteration_method) do |call| self.delay(retry: false, queue: 'low').handle_new_call(sync_id, call.id) end unless updated_calls.empty? $redis.with { |r| r.set 'robotargeter:calls:last_updated_at', updated_calls.last.updated_at } end execution_time_seconds = ((DateTime.now - started_at) * 24 * 60 * 60).to_i yield( updated_calls.size, updated_calls.pluck(:id), { scope: 'robotargeter:calls:last_updated_at', scope_limit: Settings.robotargeter.pull_batch_amount, from: last_updated_at, to: updated_calls.empty? ? nil : updated_calls.last.updated_at, started_at: started_at, completed_at: DateTime.now, execution_time_seconds: execution_time_seconds, remaining_behind: updated_calls_all.count }, false ) end def self.handle_new_call(sync_id, call_id) call = Call.find(call_id) contact = Contact.find_or_initialize_by(external_id: call.id, system: SYSTEM_NAME) contactee = UpsertMember.call( { phones: [{ phone: call.callee.phone_number }], firstname: call.callee.first_name, lastname: call.callee.last_name }, entry_point: "#{SYSTEM_NAME}:#{__method__.to_s}", ignore_name_change: false ) unless contactee Notify.warning "Robotargeter: Contactee Insert Failed", "Contactee #{call.inspect} could not be inserted because the contactee could not be created" return end contact_campaign = ContactCampaign.find_or_initialize_by(external_id: call.callee.campaign.id, system: SYSTEM_NAME) contact_campaign.update_attributes!(name: call.callee.campaign.name, contact_type: CONTACT_TYPE) contact.update_attributes!(contactee: contactee, contact_campaign: contact_campaign, duration: call.duration, contact_type: CONTACT_TYPE, happened_at: call.created_at, status: call.status) contact.reload if Settings.robotargeter.subscription_id && call.callee.opted_out_at subscription = Subscription.find(Settings.robotargeter.subscription_id) contactee.unsubscribe_from(subscription, reason: 'robotargeter:disposition', event_time: DateTime.now) end if Campaign.connection.tables.include?('survey_results') call.survey_results.each do |sr| contact_response_key = ContactResponseKey.find_or_initialize_by(key: sr.question, contact_campaign: contact_campaign) contact_response_key.save! if contact_response_key.new_record? contact_response = ContactResponse.find_or_initialize_by(contact: contact, value: sr.answer, contact_response_key: contact_response_key) contact_response.save! if contact_response.new_record? end end end def self.fetch_new_redirects(sync_id) ## Do not run method if another worker is currently processing this method yield 0, {}, {}, true if self.worker_currenly_running?(__method__.to_s) started_at = DateTime.now last_created_at = Time.parse($redis.with { |r| r.get 'robotargeter:redirects:last_created_at' } || '1970-01-01 00:00:00') updated_redirects = Redirect.updated_redirects(last_created_at) updated_redirects_all = Redirect.updated_redirects_all(last_created_at) updated_redirects.each do |redirect| self.delay(retry: false, queue: 'low').handle_new_redirect(sync_id, redirect.id) end unless updated_redirects.empty? $redis.with { |r| r.set 'robotargeter:redirects:last_created_at', updated_redirects.last.created_at } end execution_time_seconds = ((DateTime.now - started_at) * 24 * 60 * 60).to_i yield( updated_redirects.size, updated_redirects.pluck(:id), { scope: 'robotargeter:redirects:last_created_at', scope_limit: Settings.robotargeter.pull_batch_amount, from: last_created_at, to: updated_redirects.empty? ? nil : updated_redirects.last.created_at, started_at: started_at, completed_at: DateTime.now, execution_time_seconds: execution_time_seconds, remaining_behind: updated_redirects_all.count }, false ) end def self.handle_new_redirect(sync_id, redirect_id) redirect = Redirect.find(redirect_id) payload = { cons_hash: { phones: [{ phone: redirect.callee.phone_number }], firstname: redirect.callee.first_name, lastname: redirect.callee.last_name }, action_name: redirect.campaign.name, action_type: CONTACT_TYPE, action_technical_type: 'robotargeter_redirect', external_id: redirect.campaign.id, create_dt: redirect.created_at } Member.record_action(payload, "#{SYSTEM_NAME}:#{__method__.to_s}") end def self.fetch_active_campaigns(sync_id, force: false) ## Do not run method if another worker is currently processing this method yield 0, {}, {}, true if self.worker_currenly_running?(__method__.to_s) active_campaigns = IdentityRobotargeter::Campaign.active iteration_method = force ? :find_each : :each active_campaigns.send(iteration_method) do |campaign| self.delay(retry: false, queue: 'low').handle_campaign(sync_id, campaign.id) end yield( active_campaigns.size, active_campaigns.pluck(:id), {}, false ) end def self.handle_campaign(sync_id, campaign_id) campaign = IdentityRobotargeter::Campaign.find(campaign_id) contact_campaign = ContactCampaign.find_or_initialize_by(external_id: campaign.id, system: SYSTEM_NAME) contact_campaign.update_attributes!(name: campaign.name, contact_type: CONTACT_TYPE) campaign.questions.each do |k,v| contact_response_key = ContactResponseKey.find_or_initialize_by(key: k, contact_campaign: contact_campaign) contact_response_key.save! if contact_response_key.new_record? end end end
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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' module AWS class DynamoDB describe Errors do context 'generated error classes' do let (:error_class) { Errors::Foo } it 'should include DynamoDB::Errors::ModeledError instead of AWS::Errors::ModeledError' do error_class.should include(Errors::ModeledError) error_class.should_not include(AWS::Errors::ModeledError) end it 'should have an error code matching its class name' do error_class.new.code.should == "Foo" end it 'should have the error code as its default message' do error_class.new.message.should == "Foo" end it 'should store the request object' do request = double("request") error_class.new(request).http_request.should == request end it 'should store the response' do response = double("response", :status => 200, :body => "{}") error_class.new(nil, response).http_response.should == response end it 'should parse the response body to get the message' do response = double("response", :status => 200, :body => '{"message":"FOO"}') error_class.new(nil, response).message.should == "FOO" end it 'should default to the code if the response body does not contain a message' do response = double("response", :status => 200, :body => '{}') error_class.new(nil, response).message.should == "Foo" end it 'should default to the code if the response body message is null' do response = double("response", :status => 200, :body => '{"message":null}') error_class.new(nil, response).message.should == "Foo" end it 'should include ClientError if the status code is less than 500' do response = double("response", :body => "{}", :status => 499) error_class.new(nil, response).should be_kind_of(Errors::ClientError) error_class.new(nil, response).should_not be_kind_of(Errors::ServerError) end it 'should include ServerError if the status code is greater than or equal to 500' do response = double("response", :body => "{}", :status => 500) error_class.new(nil, response).should be_kind_of(Errors::ServerError) error_class.new(nil, response).should_not be_kind_of(Errors::ClientError) end end end end end
require "application_system_test_case" class AnalysisRequestItemsTest < ApplicationSystemTestCase setup do @analysis_request_item = analysis_request_items(:one) end test "visiting the index" do visit analysis_request_items_url assert_selector "h1", text: "Analysis Request Items" end test "creating a Analysis request item" do visit analysis_request_items_url click_on "New Analysis Request Item" fill_in "Analysis", with: @analysis_request_item.analysis_id fill_in "Analysis request", with: @analysis_request_item.analysis_request_id fill_in "Price", with: @analysis_request_item.price click_on "Create Analysis request item" assert_text "Analysis request item was successfully created" click_on "Back" end test "updating a Analysis request item" do visit analysis_request_items_url click_on "Edit", match: :first fill_in "Analysis", with: @analysis_request_item.analysis_id fill_in "Analysis request", with: @analysis_request_item.analysis_request_id fill_in "Price", with: @analysis_request_item.price click_on "Update Analysis request item" assert_text "Analysis request item was successfully updated" click_on "Back" end test "destroying a Analysis request item" do visit analysis_request_items_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Analysis request item was successfully destroyed" end end